Home > Software design >  Possible to filter a queryset by its ForeignKey related_name objects?
Possible to filter a queryset by its ForeignKey related_name objects?

Time:03-24

I have a simple model:

class Object(models.Model):
  name = CharField()
  root = ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL)

I create a few objects:

parent1 = Object.create(name="parent1")
o1 = Object.create(name="1", root=parent1")

parent1.object_set.all() # Returns queryset with o1

Is it possible to filter a queryset by its ForeignKey's related_name objects (i.e. object_set)? Something like:

Object.objects.filter(object_set__name="1") # To return parent1

I get the following error: Cannot resolve keyword 'object_set' into field.

I understand I could do Object.object.get(name="1").root but that results in additional queries which could really add up in my specific use case.

CodePudding user response:

Use:

Object.objects.filter(object__name="1")`

instead of:

Object.objects.filter(object_set__name="1")

How to determine the lookup name is described in the documentation:

While it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model.

  • Related