在django关系中来回走动

时间:2014-12-17 11:24:51

标签: python django foreign-key-relationship

我在django模型之间有以下关系

class Customer(models.Model):
    #fields

class Tooth(models.Model):
    #fields
    customer = models.ForeignKey(Customer)

class Peri(models.Model):
    #fields
    customer = models.ForeignKey(Customer)

class PeriTask(models.Model):
    #fields
    tooth = models.ForeignKey(Tooth, related_name="peritasks")
    peri = models.ForeignKey(Peri, related_name="peritasks")

我似乎无法掌握反向关系。我的意思是我可以通过`tooth.peritasks.all()获得所有peritasks特定牙齿的一部分。但是考虑到一个特定的Peri实例,我怎样才能过滤掉那个周围的牙齿?有点像(我知道它不正确)

Tooth.objects.filter(peritask__peri=peri) #this won't work I know just as an example to show what I mean   

1 个答案:

答案 0 :(得分:1)

事实上,PeriTooth PeriTask模型之间存在多对多的关系。最简单的方法是明确声明这种关系(在ToothPeri中),以便orm知道它为模型添加适当的描述符,cf https://docs.djangoproject.com/en/1.7/topics/db/models/#intermediary-manytomany:< / p>

class Tooth(models.Model):
    #fields
    customer = models.ForeignKey(Customer)
    peris = models.ManyToManyField("Peri", through="PeriTask")

然后,您可以使用peri访问与theeth相关的peri.tooth.all()