0

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!

Abhijit Ghate
  • 382
  • 3
  • 16

1 Answers1

0

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

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34
  • I already tried that but it shows me an error saying `FieldError: Cannot resolve keyword 'Model2_set' into field.` – Abhijit Ghate Oct 09 '18 at 09:50
  • @AbhijitGhate - thanks, this really should have been included in the original question, because it's the most obvious way to do this, and the error is (to me, at least) unexpected. I can't immediately think why that would be happening, but I'm sure someone else here could help! – Robin Zigmond Oct 09 '18 at 09:55
  • 1
    You need to use the *lower-cased* name of Model2. This would be clearer if you used actual model names, and showed actual code and errors. – Daniel Roseman Oct 09 '18 at 10:17
  • thanks @DanielRoseman, can't believe I missed that (a combination of the fact that I haven't used Django in nearly a year, and normally use an all-lowercase `related_name` anyway). I'll edit the answer – Robin Zigmond Oct 09 '18 at 10:20
  • @DanielRoseman I just tried that too. But the error still persists. – Abhijit Ghate Oct 09 '18 at 10:36