Myzel394
Myzel394

Reputation: 1317

Django - Filter when Case is false

I have a model Article. That should be filtered. Here's the condition:

If the request is NOT an author, all articles with pub_date lte now will be visible.

If the request is an author, all articles with pub_date lte now will be visible PLUS articles from the authors (regardless of pub_date).

In simple language: Everyone should only see the articles, which hasn't been published, but authors can also see their articles.


I thought I could annotate the articles and then somehow filter on them, but I have no idea how to continue or how to do it. authors is a m2m field.

articles = articles.annotate(
                can_see=Case(
                    When(authors__id__in=[request.user.id], then=Value(True)),
                    default=False,
                    output_field=BooleanField()
                )
            )

Upvotes: 0

Views: 51

Answers (1)

ivissani
ivissani

Reputation: 2664

From what I can deduce of your code you can use a simple OR in your filter. Essentially you would do something like:

from django.utils import timezone
from django.db.models import Q

now = timezone.now()
to_show = articles.filter(Q(authors__id=request.user.id) | Q(pub_date__lte=now))

This performs a logical or between the tow criteria enclosed in the Q() objects. What this query is saying is "bring every article that either has an author whose id matches the user id in the request or whose publication date is less than or equal to the current date"

Please take a look at the documentation on querying the databse.

Upvotes: 1

Related Questions