Querying RelatedManager objects

2k Views Asked by At

I have models such as

class Model1(models.Model):
    f1 = models.DateField(null=True, blank=True)
    f2 = models.CharField(max_length=100,null=True, blank=True)
    f3 = models.CharField(max_length=100,null=True, blank=True)

class Model2(models.Model):
    x = models.ForeignKey(Model1)
    f4 = models.CharField(null=True, blank=True)
    f5 = models.CharField(max_length=100,null=True, blank=True)

and my admin.py reads

class Model2Inline(admin.TabularInline):
    model = Model2
    search_fields = ('f5',)
    extra = 1
class Model1Admin(admin.ModelAdmin):
    list_display = ('f1', 'f2')
    search_fields = ['f1']
    inlines = [Model2Inline]

I wish to filter Model1 based on specific values of the field f4

Something like

results = Model1.objects.filter(where f4 = "some_specific_value")

which is intended to result a query set containing instances of Model1 in which inline Model2's will have f4 set to some_specific_value

Thanks!

1

There are 1 best solutions below

5
On

this should work (edited, thanks to @DanielRoseman for pointing out what I was missing):

results = Model1.objects.filter(model2_set__f4="some_specific_value")

You could also give the ForeignKey attribute a related_name keyword argument, so that you can reference Model2 from Model1 by a more understandable name than model2_set.

See documentation at https://docs.djangoproject.com/en/2.1/topics/db/queries/#related-objects