Search code examples
pythondjangointrospectiondjango-haystack

django - having model class how to get list of all fields, their types and parameters passed?


lets assume I have following model:

class Note(models.Model):
    user = models.ForeignKey(User)
    pub_date = models.DateTimeField()
    title = models.CharField(max_length=200)
    body = models.TextField()

    def __unicode__(self):
        return self.title

I need a function that will work like this:

print inspectModelClass(Note)

>>> {user:('ForeignKey', {null:False, unique:False, blank:False...}), pub_date:('DateTimeField',{null:False, unique:False,...})...}

I don't know how to list only instances of django.model.field, how to get their names, proper types (BooleanField, CharField, etc.) and their properties like null, unique, max_chars etc.

Can you help me with that?

The reason I need this is that having such a function I would be able to dynamically create Index classes for django-haystack.


Solution

  • You can get Model fields properties easily using the class Metadata.

    MyModel._meta.fields
    

    return a list of the fields. Every field in this list has your well known attributes (name, verbose_name etc.)