Folks, I'm trying to get the type of the Model's attribute. For example, consider the following model below:
class Option(models.Model):
option_text = models.CharField(max_length=400)
option_num = models.IntegerField()
# add field to hold image or a image url in future
def __unicode__(self):
return self.option_text
I'm setting each of the attribute of this model programmatically. I need to access the type of the attribute. For example, for option_num, I should be able to get "IntegerField" or an equivalent.
I saw the meta api, and read the source, too. But I don't see a way to retrieve the internal type.
model._meta.get_field(attr_value).getInternalType() => gives me an error.
Getting an "'CharField' object has no attribute 'get Internal Type'".
To clarify a little, the reason I need to know whether an attribute is a string or an int is because, if from the front end, I get a string, which is actually an integer, i would like to typecast it.
Help?
Thanks!
you are close with the meta option but you need to remember some Python PEP8 Love.
if you have a model like this:
class Client(models.Model):
code = models.IntegerField()
name = models.CharField(max_length=96)
...
...
you can get the type name with:
Client._meta.get_field('code').get_internal_type()
u'IntegerField'
or you can get the type with:
type(Client._meta.get_field('name'))
django.db.models.fields.CharField
directly like a Class method, not only from the class instance. your choice.
The point is use
model._meta.get_field(attr_name).get_internal_type()
instead of
model._meta.get_field(attr_value).getInternalType()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With