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开发者_如何学C:
#Do something cool
and customers from pizza within this new app.
How can I do that ?
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')
精彩评论