2

How can I get class attribute's type in Python the same way I do it in Java with this code?

Field f = ClassName.class.getDeclaredField("attr_name");
Class<?> ftype = f.getType();

With

c = ClassName()
c.__dict__

I can get all attributes name and values, but not their types.

More specifically, using Django, if I have two classes, say Poll and Choice, defined as follow

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

How can I know if a class has a models.ForeignKey as attribute's type and to which other class it points?

I need as output something like:

# attribute poll in class Choice is a ForeignKey type
# and it points to Poll model
Choice.poll -> Poll
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
mrnfrancesco
  • 1,017
  • 8
  • 26

2 Answers2

3

To get the type of an object in Python, use type. From there, you can use __name__ to get the name of the class as a string:

>>> class MyClass(object):
...     pass
...
>>> obj = MyClass()
>>> type(obj)
<class '__main__.MyClass'>
>>> type(obj).__name__
'MyClass'
Rob Watts
  • 6,866
  • 3
  • 39
  • 58
3

To get the class name of a related model, use rel.to:

print Choice.poll.field.rel.to.__name__   # prints 'Poll'

Or, this way:

field = Choice._meta.get_field_by_name('poll')[0]
print field.rel.to.__name__  # prints 'Poll'

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195