Django 如何使用 ManyRelatedManager
我有 2 个不同的应用,并且没有特别的理由互相交谈。 这意味着我不想在任一应用程序中导入任一名称。所有的工作都应该是 在胶水应用程序中。
我想编写一个粘合应用程序,通过 ManyToManyField 连接到特定模型,例如:
在应用程序客户中,
class Customer(models.Model):
...
在应用程序披萨中,
class Pizza(models.Model):
...
然后我想编写这样的披萨销售应用程序:
class PizzaSold(models.Model):
customer = models.ForeignKey(related_name='pizzas')
pizza = models.ForeignKey(related_name='customers')
objects = ManyRelatedManager()
这样我就可以从 在这个新应用程序中,直接客户
pizza = Pizza.objects.all()[0]
for customer in pizza.customers:
#Do something cool
和披萨客户。
我怎样才能做到这一点?
I have 2 apps that are distinct and have no particular reason to talk to each other.
This means I don't want to import either name in either app. All the work should be
within a glue app.
I would like to write a glue app that would join to particular models via a ManyToManyField like:
In app customers,
class Customer(models.Model):
...
In app pizzas,
class Pizza(models.Model):
...
Then I would like to write the pizza-selling app that would go like this:
class PizzaSold(models.Model):
customer = models.ForeignKey(related_name='pizzas')
pizza = models.ForeignKey(related_name='customers')
objects = ManyRelatedManager()
so I can access pizzas from customers directly
pizza = Pizza.objects.all()[0]
for customer in pizza.customers:
#Do something cool
and customers from pizza within this new app.
How can I do that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 ManyToManyField 会怎么样?为客户模型中出售的披萨建模?
另外,如果您想向您的客户添加额外的数据 ->披萨关系,通过参数通过参数指定映射类:
同样,使用
lated_name
也应该可以与ManyToManyFields
配合使用。例如:What if you used ManyToManyField to model pizzas sold inside Customer model?
Also, if you wish to add extra data to your customer -> pizza relations, specify the mapping Class with through parameter:
Simlarly, using
related_name
should work just fine withManyToManyFields
as well. For instance: