[Fixed]-Check for existence and active state in django filter

1👍

Since you are already filtering on is_active=1, you don’t need to check later for users_like[0].is_active because at this time you only have all the likes which are active.

The alternative way would be to get all the likes for the user first (which should ideally be 1 or 0)

user_likes = article.articlelike_set.filter(user=request.user)

now, first you can check if an like for the user exists or not:

user_likes.exists() # user has liked an article

or, if an active like for an user exists or not:

user_likes.filter(is_active=1).exists() # user has liked an article and it is active

On a completely different note, if you use related_name your code would look more beautiful:

 article = models.ForeignKey('article.Article', related_name='likes')

 # to filter on likes
 article.likes.filter(...)
👤AKS

Leave a comment