Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all related Django model objects

How can I get a list of all the model objects that have a ForeignKey pointing to an object? (Something like the delete confirmation page in the Django admin before DELETE CASCADE).

I'm trying to come up with a generic way of merging duplicate objects in the database. Basically I want all of the objects that have ForeignKeys points to object "B" to be updated to point to object "A" so I can then delete "B" without losing anything important.

Thanks for your help!

like image 853
erikcw Avatar asked Feb 10 '10 01:02

erikcw


People also ask

How do you get all related models in django?

To get all related Python Django model objects, we use the NestedObjects class. to create a NestedObjects object with the using argument set to the database name. Then we call collect with an array of objects to get the related objects. Finally, we get the data from collector.

Is there a list field for django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.

What is objects all () django?

For example, Blog.objects.all() returns a QuerySet that contains all Blog objects in the database.

What is Relatedmanager django?

A “related manager” is a manager used in a one-to-many or many-to-many related context. This happens in two cases: The “other side” of a ForeignKey relation. That is: from django.db import models class Blog(models.


1 Answers

Django <= 1.7

This gives you the property names for all related objects:

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:         # do something with related object instance 

I spent a while trying to figure this out so I could implement a kind of "Observer Pattern" on one of my models. Hope it's helpful.

Django 1.8+

Use _meta.get_fields(): https://docs.djangoproject.com/en/1.10/ref/models/meta/#django.db.models.options.Options.get_fields (see reverse in the _get_fields() source also)

like image 142
robbles Avatar answered Sep 25 '22 00:09

robbles