views:

42

answers:

1

I've defined a User class which (ultimately) inherits from models.Model. I want to get a list of all the fields defined for this model. For example, phone_number = CharField(max_length=20). Basically, I want to retrieve anything that inherits from the Field class.

I thought I'd be able to retrieve these by taking advantage of inspect.getmembers(model), but the list it returns doesn't contain any of these fields. It looks like Django has already gotten a hold of the class and added all its magic attributes and stripped out what's actually been defined. So... how can I get these fields? They probably have a function for retrieving them for their own internal purposes?

+3  A: 
model._meta.get_all_field_names()

That should do the trick.

That requires an actual model instance. If all you have is a subclass of django.db.models.Model, then you should call myproject.myapp.models.MyModel._meta.get_all_field_names()

Bryan Ross
Wanted the objects too, not just their names. This seems to be available in `model._meta.fields` though, and their names are retrievable with `field.name` it seems. I just hope this is the most stable way to retrieve this info :)
Mark
not entirely sure. The underscore seems to indicate it's an internal API, would be cool if the Django guys promoted this up to an actually public method call on `django.db.models.Model`. I'll dig into it and see what I can find
Bryan Ross
I guess doing it via the `_meta` attribute is the only way... Additionally look into `_meta.many_to_many` for ManyToMany fields!
lazerscience
Glad to help. And Mark, how 'bout puttin a little 90% accept rate love on this answer?
Bryan Ross
@lazerscience: I was just going to ask about those! Because I noticed the Django admin has more fields than what I retrieved from `_meta.fields`. @Bryan: Of course :) I review my questions fairly often to accept the best answer... but some of them still don't, and probably never will. Wish I could close em without needing 5 votes.
Mark
@Mark Thank you very much :)
Bryan Ross