Sumit Jha
Sumit Jha

Reputation: 2195

Django template 'IF' condition

I want to do something like

{% if "sumit" in feed.like.person.all %}

But this gives me TemplateSyntaxError. How can I do this in Djagno ?

(Basically, I want to check if 'sumit' exists in feed.like.person.all)

Here are my relevant models.

class Feed(models.Model):
    name = models.CharField(max_length=120)
    text = models.CharField(max_length=1200)
    timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
    updated = models.DateTimeField(auto_now=False, auto_now_add=True)


class Like(models.Model):
    feed = models.OneToOneField(Feed)
    counter = models.PositiveIntegerField()
    person = models.ManyToManyField(settings.AUTH_USER_MODEL, null=True, blank=True)

Upvotes: 2

Views: 716

Answers (2)

Rahul Gupta
Rahul Gupta

Reputation: 47866

I think you intended to check the following:

# check if current user likes a feed
{% if request.user in feed.like.person.all %}

But if you are checking this for multiple feeds, then this method becomes inefficient. For multiple feeds, better approach is to use Annotations as mentioned by @AKS.

Upvotes: 3

AKS
AKS

Reputation: 19801

Your approach to check if a user likes a feed within the templates by querying for each feed is very inefficient.

I would suggest using Conditional Expressions to annotate each feed while fetching the queryset:

from django.db.models import BooleanField, Case, When, Value

feeds = Feed.objects.all().annotate(
             is_liked=Case(
                When(like__person=request.user, then=Value(True)),
                default=Value(False),
                output_field=BooleanField()))

This way you would be getting everything in one query only. And, then in the template you can just check is_liked on the feed:

{% if feed.is_liked %}You like this.{% endif %}

I haven't really executed this query but looking at the documentation it would be something similar.

Upvotes: 2

Related Questions