views:

69

answers:

1

Hi All,

Given a Django model, I'm trying to list all of it's fields. I've seen some examples of doing this using the _meta model attribute, but doesn't the underscore in front of meta indicate that the _meta attribute is a private attribute and shouldn't be accessed directly? ... Because, for example, the layout of _meta could change in the future and not be a stable API?

Is _meta an exception to this rule? Is it stable and ready to use or considered bad practice to use it? Or is there a function or some other way to introspect the fields of a model without using the _meta attribute? Below is a list of some links showing how to do this using the _meta attribute

Any advice is much appreciated.

http://stackoverflow.com/questions/763558/django-object-get-set-field

http://www.djangofoo.com/80/get-list-model-fields

http://stackoverflow.com/questions/2384436/how-to-introspect-django-model-fields

+3  A: 

_meta is private, but it's relatively stable. There are efforts to formalise it, document it and remove the underscore, which might happen before 1.3 or 1.4. I imagine effort will be made to ensure things are backwards compatible, because lots of people have been using it anyway.

If you're particularly concerned about compatibility, write a function that takes a model and returns the fields. This means if something does change in the future, you only have to change one function.

def get_model_fields(model):
    return model._meta.fields

I believe this will return a list of Field objects. To get the value of each field from the instance, use getattr(instance, field.name).

Will Hardy
You should also be aware of he fact, that if you also need the many-to-many fields you need to access `model._meta.many_to_many`!
lazerscience
Thank you Will. Good to know that other people are using _meta as well. I like the idea of having a wrapper function. Lazerscience, thank you also. Good to know there is a nice method to get the many_to_many fields. Joe
Joe J