如何在接收模型的末端明确显示Django ManyToMany关系 [英] How to make Django ManyToMany relationships explicit on the receiving model's end

查看:68
本文介绍了如何在接收模型的末端明确显示Django ManyToMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关系,尤其是 ManyToMany ,总是让我有些困扰。特别是,由于该关系仅在其中一个模型中定义,因此无法从配对模型中看出它可能隐藏的其他关系。

Relationships, particularly ManyToMany, in Django have always bothered me somewhat. 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.

例如,来自 Django文档

class Topping(models.Model):
    # ...

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)

您可以通过查看代码可以知道,我会在 Pizza.toppings 处找到披萨的相关浇头。但是您不能告诉我,我可以在 Topping.Pizza_set 中分辨出哪些披萨具有浇头-您必须查看 Pizza 类来查看此内容。

You can tell from looking at the code that I'd find out the relevant toppings for a pizza at 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.

因此,通过查看浇头,我实际上并不知道它具有的所有字段。

As a result, by looking at Toppings, I don't actually know the full range of fields that it has.

有没有办法解决这个问题或使其更明确?还是我缺少什么?

Is there any way around this or to make it more explicit? Or is there something that I'm missing?

推荐答案

这似乎是DRY原理不可避免的副作用。我不知道有什么方法可以声明性地显示这些关系中的对称性(除了通过评论等)。如果您真的想使事情变得明确,则可以将关系放在自己的表中(无论如何,Django都会在后台进行处理),例如:

This seems to be an unavoidable side effect of the DRY principle. 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:

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='+')

...但是当然,您会失去一些方便的ORM。

... but of course then you'd lose some of the convenience of the ORM.

这篇关于如何在接收模型的末端明确显示Django ManyToMany关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆