About Annotating Conditions
To detect in the list view which items belong to a certain category, you can use an annotation like this:
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:
<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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.