Kobz
Kobz

Reputation: 469

How to get properties of a model attribute?

Let's say that I have a class such as :

class MyClass(models.Model):
    attributeA = models.CharField(max_length=100)
    attributeB = models.IntegerField()
    attributeC = models.CharField(max_length = 150, blank=True, nullable = True)
    attributeD = models.ForeignKey('ModelB',related_name='FK_modelB')
    attributeE = models.ManyToManyField('ModelC')

What I want to do is to get the properties of every attribute, not just the name that I got with :

my_instance._meta.get_all_field_name()

(which gave me a list of attributes names). No, what I want is, for every attribute, know what is his type (CharField,IntegerField, ForeignKey, ManyToManyField...), who's related if it's a ForeignKey / ManyToManyField and all the meta data such as max_length and so on.

The aim of it is to serialize a class into a XML and the representation in the XML will be different if it's a ManyToManyField, a ForeignKey or a simple value.

By the way, If anyone know a great class serializer to XML, it would help me a lot !

Thanks for your responses !

Upvotes: 1

Views: 2250

Answers (2)

aysum
aysum

Reputation: 71

You can get attributes of a specific field by using get_field()

MyClass._meta.get_field('attributeA').max_length

Upvotes: 0

ndpu
ndpu

Reputation: 22561

Django models _meta.fields is fields list that you can access to get field attributes:

>>> from django.contrib.auth.models import User
>>> u = User.objects.all()[0]
>>> u._meta.fields[1].__class__.__name__
'CharField'
>>> u._meta.fields[1].name
'username'
>>> u._meta.fields[1].max_length
30
>>> u._meta.fields[1].blank
False
# ...

Upvotes: 2

Related Questions