how can I iterate and retrieve all fields of a django model?
I know that foo.item._meta.get_all_field_names()
brings me all field names.
How can I access those fields (incl. their actual values) on a model instance? (Except the normal notation foo.fieldname
).
I need this in order to build a custom output for my model including its manyTomany relations. Any ideas?
Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields.
Each field in your model should be an instance of the appropriate Field class. Django uses the field class types to determine a few things: The column type, which tells the database what kind of data to store (e.g. INTEGER , VARCHAR , TEXT ).
Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.
A model is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection. Models are defined in the app/models.py (in our example: myapp/models.py)
How about:
getattr(foo.__class__, <field_name>)
This should give you the field object, rather than the value in the given model instance. If you want the value of the field in the given model insance you can call it like this:
getattr(foo, <field_name>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With