M
M
MalekBV2020-05-25 12:23:15
Django
MalekBV, 2020-05-25 12:23:15

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"""
    ...


In the template I have:
{% for product in products %} ...

I think I can do it like this {% if product in user.favorite.all %}
But I don't know how to get all products instead of favorites

How can i do it in templates?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
noremorse_ru, 2020-05-25
@noremorse_ru

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 question

Ask a Question

731 491 924 answers to any question