Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django How to use ManyRelatedManager

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 ?

like image 628
Narsilou Avatar asked Oct 11 '22 22:10

Narsilou


1 Answers

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')
like image 82
jsalonen Avatar answered Oct 14 '22 02:10

jsalonen