Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what model should I add the ManyToManyField?

I read the documentation about many-to-many relationships and the examples. What I could not find is a hint on where to put the ManyToManyField. In my case I have an extended user model Client and a model Pizza. Every client may mark one or more pizzas as favourites. Those are my two models:

from django.db import models
from django.contrib.auth.models import User

class Client(models.Model):
    user = models.OneToOneField(User)
    #? favourite_pizza = models.ManyToManyField()

class Pizza(models.Model):
    name = models.CharField(max_length=255)
    #? favourite_pizza = models.ManyToManyField()

In what model should I add the ManyToManyField? Does it matter?

PS The important information is how many favourite pizzas a client has (and which). It is less important how many clients marked a pizza as a favourite (and who). Consequently I would chose to put the ManyToManyField in the Client class.

like image 483
Daniel Avatar asked Sep 12 '13 20:09

Daniel


People also ask

What is ManyToManyField Django?

ManyToManyRel is used by the ManyToManyField to implement the relationship object for the Field base class which it extends.

How do you implement many-to-many relationships in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.

WHAT IS models ForeignKey?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db.

What is through model in Django?

The through attribute/field is the way you customize the intermediary table, the one that Django creates itself, that one is what the through field is changing. Save this answer.


2 Answers

From the Django documentation:

Generally, ManyToManyField instances should go in the object that’s going to be edited on a form.

like image 115
SaeX Avatar answered Sep 19 '22 13:09

SaeX


Technically it does not matter. The question is from which model-side you will query the database.

like image 25
Daniel Avatar answered Sep 20 '22 13:09

Daniel