Answer the question
In order to leave comments, you need to log in
Django, how to know if a user liked a post or not?
I have 2 models. Product, Favorite (favorite - like like)
Favorite is related to Product and User. I need to check in the templates if the user has a relationship with the product to insert a like button or remove it."
class Favorite(models.Model):
"""User favorite products"""
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='favorites')
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='favorites')
class Product(models.Model):
"""Store product"""
...
Answer the question
In order to leave comments, you need to log in
Add a list of all product ids that a particular user has in their favorites, and cache it well so as not to pull the base every time for nothing
like:
favorites = user.favorites.all().values_list('id', flat=True
) of the product, check if product.id in favorites: ...
Better yet, make the in_favorites method on the Product, which will return True or False, but here you also need to get templatetags
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question