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,430 points
61 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
• 12,280 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,500 points

edited Dec 18, 2018 by Nymeria 413 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
53 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,160 points
784 views
0 votes
1 answer
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
106 views
0 votes
1 answer
0 votes
1 answer

Host not allowed

Go to your project directory cd project cd project ALLOWED_HOSTS ...READ MORE

answered Aug 9, 2018 in AWS by Priyaj
• 56,160 points
89 views
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
• 12,280 points
120 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
• 12,280 points
22 views