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
3,251 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,880 points
915 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,880 points
1,310 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,970 points
112 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,540 points

edited Dec 18, 2018 by Nymeria 4,659 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
1,075 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,830 points
830 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,300 points
3,247 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
272 views