How can I store a list of Livre
for each User
in my Django model.py
?
Which looks like:
class Livre(models.Model):
auteur = models.ForeignKey(Auteur)
titre = models.CharField(max_length=50)
genre = models.ForeignKey(Genre)
publish_date = models.DateField()
I want my User
can as much Livre
as they want (0 is possible):
from django.db import models
from django.contrib.auth.models import User
class Lecteur(User):
bibliotheque = models.??????(Livre)
... without touching the Livre
model.
To make is short I want a OneToMany relationship from User
to Livre
.
Just add a ManyToManyField
in the User model.
You want in fact a ManyToMany
relation rather than a OneToMany
relation, because you want multiple users be able to have the same Livre linked to them, right?
If not, you could restrict that by overriding the save()
method (just add checks), or you could argue that this should be in fact the responsibility of Livre, and add ForeignKey
there.
You can find more about ManyToManyField
here: https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/