How to get all related Django model objects in Python?

0 votes
How can I get a list of all the model objects that have a Foreign Key pointing to an object?

Thanks for your help!
Nov 14, 2018 in Python by Anirudh
• 2,060 points

edited Dec 18, 2018 by Anirudh 399 views

1 answer to this question.

0 votes

This actually gives you the property names for all objects (related):

links = [rel.get_accessor_name() for rel in a._meta.get_all_related_objects()]

You can then use something like this to get all related objects:

for link in links:
    objects = getattr(a, link).all()
    for object in objects:
        # Object instance based on requirement

Hope it's helpful.

answered Nov 14, 2018 by Nymeria
• 3,500 points

edited Dec 18, 2018 by Nymeria

Related Questions In Python

0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,320 points
56 views
0 votes
3 answers

How to get the current time in Python

FOLLOWING WAY TO FIND CURRENT TIME IN ...READ MORE

answered Apr 8 in Python by rajesh
• 1,210 points
44 views
0 votes
1 answer

How to get the current time in Python

>>> import datetime >>> datetime.datetime.now() datetime(2018, 25, ...READ MORE

answered Jul 25, 2018 in Python by Frankie
• 9,810 points
35 views
0 votes
1 answer

How to get textual output when using exceptions in Python?

Hi, the answer is pretty simple.  Without the ...READ MORE

answered Jan 17 in Python by Nymeria
• 3,500 points
13 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 124 views
0 votes
1 answer

How to run django unit-tests on production database in Python?

In case someone googles here searching for ...READ MORE

answered Nov 28, 2018 in Python by Nymeria
• 3,500 points
38 views
0 votes
1 answer

How to print objects of class using print function in Python?

It can be done as shown below: class Element: ...READ MORE

answered Dec 3, 2018 in Python by Nymeria
• 3,500 points

edited Dec 19, 2018 by Nymeria 124 views