modeling favorite django apps from two different models

How about something like:

class User(...):

    first_name = models.CharField(...)
    ....

class Movie(models.Model):

    title = models.CharField(...)
    ...

class Favorite(models.Model):

    user = models.ForeignKey('User', related_name='favorites', ...)
    movie = models.ForeignKey('Movie', related_name='favorites', ...)

Then we can do:

# a particular user's favorite movies:
user = User.objects.get(id='the_user_id')
user.favorites.values('movie')

# number of users who have favorited a particular movie:
movie = Movie.objects.get(id='the_movie_id')
movie.favorites.count()

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top