Django model iterate fields

+1 vote
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,910 points
5,147 views

1 answer to this question.

+1 vote
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,300 points

Related Questions In Python

0 votes
1 answer

How do I include related model fields using Django Rest Framework?

Hello @kartik, The simplest way is to use the ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,840 points
3,632 views
0 votes
1 answer

How to extend the User model with custom fields in Django?

Hello @kartik, Define an object manager for your ...READ MORE

answered Aug 3, 2020 in Python by Niroj
• 82,840 points
3,174 views
0 votes
1 answer

Unable to access UserProfile model fields in templates in Django.

Use {{ request.user.get_profile.whatever }}. Django's templating language ...READ MORE

answered Nov 13, 2020 in Python by Gitika
• 65,770 points
573 views
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,560 points

edited Dec 18, 2018 by Nymeria 6,845 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,300 points
2,522 views
0 votes
0 answers

"Post Image data using POSTMAN"

I am trying to POST data to ...READ MORE

May 21, 2022 in Others by Kichu
• 19,040 points
1,093 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
1,969 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, 2019 in Python by SDeb
• 13,300 points
5,061 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,300 points
1,113 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP