'Filter in the template if the product is in wishlist or no. Django ecommerce website

I had a question about django-templates. I was wondering about if we can add a filter in django template. I want to know if the product is in wishlist or no while rendering it. So, how can we know if it's in the wishlist or no? views.py

def store(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']
    categories = Category.objects.all()
    products = Product.objects.all()
    if request.user.is_authenticated:
        user=request.user
        wishedProducts = Wishlist.objects.filter(user=user)
    else:
        wishedProducts = {}

    """popularnye = Product.objects.filter(popularnye=True)"""
    context = {'products':products, 'cartItems':cartItems, 'order':order, 'items':items, 'categories':categories,'wishedProducts':wishedProducts}
    return render(request, 'store/store.html', context)

models.py

class Wishlist(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, verbose_name="Название товара",null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        unique_together = (
            ('user', 'product'),
        )
        verbose_name = 'Избранные'
        verbose_name_plural = "Избранные"

    def __str__(self):
        return str(self.product)

template

    {% for product in products %}
                      <div class="store col-lg-3 col-6">
                        <div class="single-product">
                          <div class="single-product">
  <div class="header-single-product">
  <p style="margin-top:-10px;margin-bottom:-10px" class="code">Код: 51265</p>
  {% if product in wishedProducts.product %}
  <i class="bi bi-heart-fill addWishlist" style="color: red" data-product="{{product.id}}" data-action="add"></i>
  {% else %}
  <i class="bi bi-heart addWishlist"  data-product="{{product.id}}" data-action="add"></i>
  {% endif %}
    <i class="fa fa-balance-scale" style="margin-right:5px;"></i>

........



Solution 1:[1]

You can obtain the products with:

def store(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']
    categories = Category.objects.all()
    products = Product.objects.all()
    if request.user.is_authenticated:
        wishedProducts = Product.objects.filter(wishlist__user=request.user)
    else:
        wishedProducts = Product.objects.none()

    context = {'products':products, 'cartItems':cartItems, 'order':order, 'items':items, 'categories':categories,'wishedProducts':wishedProducts}
    return render(request, 'store/store.html', context)

This will fetch all the Products in the wishlist in a single query, and thus avoid an N+1 problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1