About Annotating Conditions

To detect in the list view which items belong to a certain category, you can use an annotation like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.db import models
from django.shortcuts import render
from posts.models import Post

def Condition(*args, **kwargs):
    return models.ExpressionWrapper(
        models.Q(*args, **kwargs),
        output_field=models.BooleanField(),
    )

def post_list(request):
    posts = Post.objects.annotate(
        is_special=Condition(
            categories__slug="special",
        )
    )
    return render(request, "posts/list.html", {"posts": posts})

Then in the template you can check for the annotated attribute:

1
2
3
4
5
<ul>
{% for post in posts %}
    <li>{{ post.title }} {{ post.is_special|yesno:"⭐️," }}</li>
{% endfor %}
</ul>

Tips and Tricks Programming Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL MySQL SQLite