kevin.w.johnson
kevin.w.johnson

Reputation: 1794

Django Many-To-One relationship filter set

I have a couple models setup like so:

Group(models.Model):
    name = models.TextField(max_length=255)

Thing(models.Model):
    location = models.TextField(max_length=255)
    group = models.ForeignKey(Group)

That's just an example to illustrate the relationship, so forgive any syntax errors.

My question is, how can find a group which has a particular set of locations? I should be able to access the Things associated with a Group by using:

Group.thing_set

Right? So is there any way I can filter based on what items are within the thing_set? I'm thinking something along the lines of this.

Group.objects.filter(thing_set.location in ["Location A", "Location B"]).all()

Hopefully this would return to me every group which contains things from both Location A and Location B. Any suggestions or a push in the right direction would be very helpful!

Thanks.

Upvotes: 3

Views: 15951

Answers (1)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

According to the documentation you have to use the name of the model as your query operator:

To refer to a “reverse” relationship, just use the lowercase name of the model.

models.py:

from django.db import models


class Group(models.Model):
   name = models.TextField(max_length=255)


class Thing(models.Model):
    location = models.TextField(max_length=255)
    group = models.ForeignKey(Group)

views.py:

from django.views.generic import ListView


class ReverseFK(ListView):
    model = Group

    def get_queryset(self):
        g = Group.objects.create(name="example")
        g.save()
        Thing.objects.create(location="here", group=g)
        return Group.objects.filter(thing__location__in=["here","there"])

Working code example on github

Upvotes: 7

Related Questions