Django model iterate fields

0 votes
I want to know 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? I need this in order to build a custom output for my model including its manyTomany relations.

Can anyone help me on how to do this?
Apr 10 in Python by ana1504.k
• 7,870 points
168 views

1 answer to this question.

0 votes
You can try the following:

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>)
answered Apr 10 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

How to get all related Django model objects in Python?

This actually gives you the property names ...READ MORE

answered Nov 14, 2018 in Python by Nymeria
• 3,520 points

edited Dec 18, 2018 by Nymeria 694 views
0 votes
1 answer

How can I iterate through two lists in Parallel

You have to use the zip function ...READ MORE

answered Apr 17, 2018 in Python by anonymous
83 views
0 votes
1 answer

Django form validation: making “required” conditional?

This is done with the clean method on the ...READ MORE

answered Aug 30, 2018 in Python by Priyaj
• 56,900 points
1,129 views
0 votes
1 answer
0 votes
1 answer

Get all tags from taggit

You can use all() to get all the tags ...READ MORE

answered Aug 5 in Python by SDeb
• 13,160 points
34 views
0 votes
1 answer

how to download and install Django rest framework?

To install Django, you can simply open ...READ MORE

answered Apr 24, 2018 in Python by Christine
• 15,790 points
159 views
0 votes
1 answer
0 votes
1 answer

How do you configure Django to send mail through Postfix?

You can do this by adding  settings.py ...READ MORE

answered Feb 25 in Python by SDeb
• 13,160 points
390 views
0 votes
1 answer

Django AllAuth gives SSLError

It can be fixed by replacing: client = ...READ MORE

answered Mar 20 in Python by SDeb
• 13,160 points
38 views