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, 2019 in Python by ana1504.k
• 7,890 points
1,353 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, 2019 by SDeb
• 13,250 points

Related Questions In Python

0 votes
1 answer
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,540 points

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

Model Form “object has no attribute 'cleaned_data'” in Django?

Hello @kartik, For some reason, you're re-instantiating the ...READ MORE

answered Apr 29 in Python by Niroj
• 34,050 points
600 views
0 votes
1 answer

Errors in fields not displaying on Django admin form?

Hiii, Here is how you can see what ...READ MORE

answered Apr 29 in Python by Niroj
• 34,050 points
70 views
0 votes
1 answer

Get all tags from taggit

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

answered Aug 5, 2019 in Python by SDeb
• 13,250 points
398 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,810 points
354 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, 2019 in Python by SDeb
• 13,250 points
1,460 views
0 votes
1 answer

Django AllAuth gives SSLError

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

answered Mar 20, 2019 in Python by SDeb
• 13,250 points
117 views