Ahmed
Ahmed

Reputation: 97

Associate additional value to a manytomanyfield

I have 2 models book and favorite

class Book(models.Model):
title = models.CharField(max_length=200)

class Favorite(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
favorites = models.ManyToManyField(Book, related_name='favorited_by')

Here a user has its own sets of favorite books. I want to associate an additional variable to each selected favorite book but how can this be done?

Upvotes: 1

Views: 86

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476554

You can define a through model: a model that is used to write many-to-many relations. But your modeling in general is a bit strange. Why do you use a OneToOneField to a User here? Isn't a Favorite a single favorite (thus the fact that a single user likes a single book:

from django.conf import settings

class Book(models.Model):
    title = models.CharField(max_length=200)
    users = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Favorite')

class Favorite(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    additional = models.IntegerField()

We thus model it as a three models:

+-------+ 1   M +------------+ N    1 +------+
| Book  |-------| Favorite   |--------| User |
+-------+       +------------+        +------+
| title |       | additional |
+-------+       +------------+

Now Favorite is thus seen as the fact that a User liked a Book. Not as one-to-one model instance attached to a User that will contain all favorites.

For more, see the documentation on the through parameter [Django-doc].

Upvotes: 1

Related Questions