Home > OS >  Django model filter elements
Django model filter elements

Time:07-01

I have four models as follows:

class modelA(models.Model):
    name = models.CharField(...)

class modelB(models.Model):
    date = models.DateTimeField(...)
    A = models.ForeignKey(modelA, ...)

class modelC(models.Model):
    
    email = models.CharField(...)
    B = models.ForeignKey(modelB, ...)

class modelD(models.Model):
    uid = models.CharField(...)
    C = models.ForeignKey(modelC)

Given modelA element id, I have to filter modelD elements based on that id. But I am not sure about how to do that.

I appreciate any ideas!

CodePudding user response:

modalD.objects.filter(C__B__A__name ='name')

when you use double underscore you filter the related Inheritance modal

CodePudding user response:

This is forward foreign key and with double underscore you can go to another field of next table to filter by id of modalA based on id we do as

modalD.objects.filter(C__B__A__id ='Your certain Id value')
  • Related