[Fixed]-Retrieving the 'many' end of a Generic Foreign Key relationship in Django


When you execute the query


this fetches all nodes that are related to well via the relationship you described in your model.

It sounds as though you want to limit the nodes returned to those that reference the Report object r via the page_content_object generic foreign key relation. Is that right? If it is, then you need to filter the nodes explicitly, like this:

r = Report.objects.get(id=1)
for well in r.wells.all():                                                                                                          
    for node in well.nodes.filter(page_object_id = r.id,
                                  page_content_type = ContentType.objects.get_for_model(r)):
        # ...

Update: I don’t know anything about TastyPie and I have to say that I don’t really understand what you are trying to do, but in Django, if there is a relation between wells and nodes, then you need to add it to your models. For example, if each Node belongs to exactly one Well, the natural thing to do would be to add a field to the Node model:

class Node(models.Model):
    # ...
    well = models.ForeignKey('Well')

and then if you want to find all nodes that belong to wells that belong to a particular Report object r, said nodes also referencing r via the generic foreign key relation, you’d issue the query:

 Node.objects.filter(well__report = r,
                     page_object_id = r.id,
                     page_content_type = ContentType.objects.get_for_model(r))

If you have to do this a lot, then a natural thing to do would be to add a method on the Report model.


A Ticker Report has many Wells, and these Wells are shared across all
Ticker Reports. What is different is that you can tie Nodes to Wells;
for a given ticker report, the only nodes that should display are the
ones that are related to that Ticker Report.

In Django, when I request a resource that has a many-to-many
relationship, I end up getting all the items in child part of the
relationship, even those not directly related to the parent. It’ll be
easier if I show you with code (classes trimmed down to only show
what’s necessary):

If I understand correctly, the node can be related to report or wells (because you mentioned related to that Ticke Report).
And you are looking for the node related to the report, not the nodes related to the wells of the report. (because you are looking for node directly related to the parent(report?) )

If I am correctly, it is quite simple:


class Report(models.Model):
    name = models.CharField(max_length=255)
    slug = AutoSlugField(_('slug'), populate_from='name')
    wells = models.ManyToManyField(Well, null=True)
    uuid = UUIDField(editable=False, blank=True, version=4, unique=True)

    nodes = generic.GenericRelation(Node)

# usage
r = Report.objects.get(id=1)
nodes = r.nodes.all()

Leave a comment