Django 如何使用 ManyRelatedManager

发布于 2024-11-09 11:12:59 字数 720 浏览 0 评论 0原文

我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鹿港小镇 2024-11-16 11:12:59

如果您使用 ManyToManyField 会怎么样?为客户模型中出售的披萨建模?

class Customer(models.Model):
   pizzas_bought = models.ManyToManyField(Pizza)

另外,如果您想向您的客户添加额外的数据 ->披萨关系,通过参数通过参数指定映射类

class Customer(models.Model):
   pizzas_bought = models.ManyToManyField(Pizza, through=PizzaSold)

class PizzaSold(models.Model):
   customer = models.ForeignKey(Customer)
   pizza = models.ForeignKey(Pizza)

同样,使用 lated_name 也应该可以与 ManyToManyFields 配合使用。例如:

class Customer(models.Model):
   pizzas_bought = models.ManyToManyField(related_name='pizzas')

What if you used ManyToManyField to model pizzas sold inside Customer model?

class Customer(models.Model):
   pizzas_bought = models.ManyToManyField(Pizza)

Also, if you wish to add extra data to your customer -> pizza relations, specify the mapping Class with through parameter:

class Customer(models.Model):
   pizzas_bought = models.ManyToManyField(Pizza, through=PizzaSold)

class PizzaSold(models.Model):
   customer = models.ForeignKey(Customer)
   pizza = models.ForeignKey(Pizza)

Simlarly, using related_name should work just fine with ManyToManyFields as well. For instance:

class Customer(models.Model):
   pizzas_bought = models.ManyToManyField(related_name='pizzas')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文