[Django]-Django Many-To-One relationship filter set

7👍

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

Leave a comment