The last extremely simple post about “How to get the object instance primary key in Django” reminded me of something.
Here’s something that I never really knew how to use until stumbling across it randomly some months ago.
Ever have a random object that you don’t know the fields of?
Or ever not remember whether your field was called short_description or shortdescription?
You can print all keys like so:
for key in your_object.__dict__.keys():
print key
For more depth: you can try dir(your_object)
The built-in function dir() is used to find out which names a module defines.
Another update from SmileyChris! Hey, theres a reason I don’t ask #Django about every little question. This way, at least, everybody gets to learn when the question is searched on google. IRC Logs never make it up there ![]()
SmileyChris:
Better to access the names via the Model meta options: [f.name for f in model_or_instance._meta.fields]
As a secondary hint, if you just need to “get” one field instance, you can use ._meta.get_field(‘field_name’)
Thanks!
1 response so far ↓
SmileyChris // May 16, 2008 at 3:03 am |
Better to access the names via the Model meta options: [f.name for f in model_or_instance._meta.fields]
As a secondary hint, if you just need to “get” one field instance, you can use ._meta.get_field(‘field_name’)