Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Attribute type of a model in Django

Tags:

python

django

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!

like image 862
abhididdigi Avatar asked Dec 27 '15 04:12

abhididdigi


2 Answers

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.

like image 118
Yonsy Solis Avatar answered Sep 28 '22 06:09

Yonsy Solis


The point is use

model._meta.get_field(attr_name).get_internal_type()

instead of

model._meta.get_field(attr_value).getInternalType()
like image 33
Serjik Avatar answered Sep 28 '22 07:09

Serjik