简体   繁体   English

在Django关系中来回走动

[英]Going back and forth in django relations

I have following relations in between django models 我在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")

I can't seem to be able to grasp the inverse relations. 我似乎无法掌握逆关系。 I mean I can get all the peritasks a specific tooth is part of with `tooth.peritasks.all(). 我的意思是,我可以通过`tooth.peritasks.all()获得所有特定牙齿的任务。 But given a specific Peri instance how can I filter the teeth that are part of that peri?Something like (I know its not correct) 但是给定特定的Peri实例,我该如何过滤属于该Peri的牙齿呢?(我知道它是不正确的)

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

You in fact have a many to many relationship between Peri and Tooth thru the PeriTask model. 实际上,通过PeriTask模型,您在PeriTooth之间具有多对多关系。 The simplest thing to do would be to explicitely declare this relationship (in either Tooth or Peri ) so the orm knows about it an add the appropriate descriptor to your models, cf https://docs.djangoproject.com/en/1.7/topics/db/models/#intermediary-manytomany : 最简单的方法是(在ToothPeri )显式声明此关系,以便orm知道这一点,然后在模型中添加适当的描述符,请参见https://docs.djangoproject.com/en/1.7/topics / db / models /#intermediary-manytomany

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

Then you have access to a given peri 's related theeth with peri.tooth.all() . 然后,您可以使用peri.tooth.all()访问给定的peri的相关theeth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM