abhididdigi
abhididdigi

Reputation: 371

Get Attribute type of a model in 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!

Upvotes: 6

Views: 6424

Answers (2)

Yonsy Solis
Yonsy Solis

Reputation: 964

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.

Upvotes: 5

Serjik
Serjik

Reputation: 10971

The point is use

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

instead of

model._meta.get_field(attr_value).getInternalType()

Upvotes: 3

Related Questions