简体   繁体   中英

Django ORM - querying many to many through models?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM