0

So I am trying to implement a user favorites system in Django. I need to store the time at which a Gallery object was favorited, so I am using Django's many to many through pattern. As you can see below I have a Gallery object which has the many to many relationship to Users who have favorited it, and the Favorite object which has a many to one with both User and Gallery. I would like to do some things like display a page with all the user's favorites on it, query a users favorites to see if a certain Gallery is in them, etc. So basically be able to get the galleries a certain user has favorited. What is the easiest way to do this with the ORM, or is this something I would need to write raw SQL for?

class Gallery(models.Model):
    favoriters = models.ManyToManyField(
    User, through='Favorite', null=True, related_name="favoriters")

    def __unicode__(self):
        return self.name        

class Favorite(models.Model):
    user = models.ForeignKey(User)
    gallery = models.ForeignKey(Gallery)
    date = models.DateField(auto_now_add=True)

Thanks.

Lucifer N.
  • 966
  • 3
  • 15
  • 34

1 Answers1

0

You can easily do this with the Django ORM.

display a page with all the user's favorites on it

user.favoriters.all()  # though that is not a good related_name

query a user's favorites to see if a certain Gallery is in them

if user.favoriters.filter(pk=my_gallery.pk).exists():
    pass

See the documentation for more examples.

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
  • Thank you, seems to work. I was confused about the purpose of that field. – Lucifer N. Apr 13 '14 at 07:54
  • @lucifer: Since that is the name by which you will get at the set of `Gallery` instances from a given `User` instance, calling it something like `galleries` or `favorites` will make everything more clear. – Kevin Christopher Henry Apr 13 '14 at 07:59
  • @lucifer: By the way, `null=True` doesn't mean anything on a M2M field. See my answer [here](http://stackoverflow.com/a/18244527/2395796) for more details. – Kevin Christopher Henry Apr 13 '14 at 08:01