[英]How to make Django ManyToMany relationships explicit on the receiving model's end
Relationships, particularly ManyToMany
, in Django have always bothered me somewhat. 关系,尤其是Django中的ManyToMany
关系,总是让我有些困扰。 In particular, since the relationship is only defined in one of the models, you can't tell from looking at the paired model what other relationships it might be hiding. 特别是,由于该关系仅在其中一个模型中定义,因此无法通过查看配对模型来判断它可能隐藏的其他关系。
For example, from the Django Documentation : 例如,来自Django文档 :
class Topping(models.Model):
# ...
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
You can tell from looking at the code that I'd find out the relevant toppings for a pizza at Pizza.toppings
. 从代码中可以看出,我在Pizza.toppings
找到了披萨的相关配料。 But you cannot tell that I would be able to tell what pizzas have a topping at Topping.Pizza_set
--you have to look at the Pizza
class to see this. 但是您不能说我能够在Topping.Pizza_set
上分辨出哪些披萨是一流的- Topping.Pizza_set
必须查看Pizza
类才能看到这一点。
As a result, by looking at Toppings
, I don't actually know the full range of fields that it has. 结果,通过查看Toppings
,我实际上并不知道它具有的所有字段。
Is there any way around this or to make it more explicit? 有什么办法可以解决这个问题,或者使其更明确? Or is there something that I'm missing? 还是我想念的东西?
This seems to be an unavoidable side effect of the DRY principle. 这似乎是DRY原理不可避免的副作用。 I don't know of any way to declaratively show the symmetry in these relations (other than by commenting and such). 我不知道有什么方法可以声明性地显示这些关系中的对称性(除了通过注释等)。 If you really want to make things explicit you could put the relationship in its own table (which Django is doing behind the scenes anyway), like: 如果您确实想使事情变得明确,则可以将关系放在自己的表中(无论如何Django都是在后台进行的),例如:
class Topping(models.Model):
# ...
class Pizza(models.Model):
# ...
class PizzaToppings(models.Model):
# '+' disables the reverse relationship
pizza = models.ForeignKey(Pizza, related_name='+')
topping = models.ForeignKey(Topping, related_name='+')
... but of course then you'd lose some of the convenience of the ORM. ...但是,当然,您会失去ORM的一些便利。
Found a way on Django's forum (lost link, sorry) 在Django的论坛上找到了一种方法(丢失链接,抱歉)
class Topping(models.Model):
explicit_pizza_set = models.ManyToManyField(Pizza, through=Pizza.toppings.through, blank=True)
class Pizza(models.Model):
toppings = models.ManyToManyField(Topping)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.