rolling stone
rolling stone

Reputation: 13016

Django: distinct QuerySet based on a related field

In my Django app I allow users to create collections of movies by category. This is represented using 3 models, Movie, Collection, and Addition (the Addition model stores movie, collection, and user instances). Simplified versions of all three models are below.

class Movie(models.Model):
    name = models.CharField(max_length=64)

class Collection(models.Model):
    name = models.CharField(max_length=64)
    user = models.ForeignKey(User)

class Addition(models.Model):
    user = models.ForeignKey(User)
    movie = models.ForeignKey(Movie)
    collection = models.ForeignKey(Collection)

So for example a user could create a collection called "80's movies", and add the movie "Indiana Jones" to their collection.

My question is: how do I display a distinct list of movies based on a set of query filters? Right now I am getting a bunch of duplicates for those movies that have been added to more than one collection. I would normally use distinct() to get distinct objects, but in this case I need distinct movies rather than distinct additions, but I need to query the Addition model because I want to allow the user to view movies added by their friends.

Am I setting up my models in an optimal way? Any advice/help would be much appreciated.

Thanks!

Upvotes: 1

Views: 3180

Answers (1)

DrTyrsa
DrTyrsa

Reputation: 31951

First. I don't think you need Addition model here. You try to create many-to-many relation, but there's documented way of doing this:

class Movie(models.Model):
    name = models.CharField(max_length=64)

class Collection(models.Model):
    name = models.CharField(max_length=64)
    user = models.ForeignKey(User)
    movies = models.ManyToManyField('Movie', blank=True, null=True)

Second. The documentation says: "To refer to a "reverse" relationship, just use the lowercase name of the model".

So the answer is (for the setup above):

Movie.objects.filter(collection__user=user).distinct()

Upvotes: 1

Related Questions