[Django]-Django GenericRelated field conditional Query raising 'GenericRelation' object has no attribute 'field'

3👍

The usual way to do that using the Django ORM is with a subquery:

Event.objects.exclude(
    content_type=note_content_type,
    object_id__in=Notes.objects.filter(active=False),
)

The sad thing is that this can be expressed in SQL with a join instead of a subquery, but the ORM doesn’t make that easy.

In some cases PostgreSQL’s query planner can optimize the subquery into a hash semi join, so don’t dismiss the subquery in preference to raw SQL without benchmarking on the data.

👤wim

1👍

Another approach is to use Conditional Expression, e.g.

from django.db import models
queryset = Event.objects.all()
queryset = queryset.annotate(
    is_inactive_note=models.Case(
        models.When(
            content_type__model='notes',
            note__active=False,
            then=models.Value(True),
        ),
        default=models.Value(False),
        output_field=models.BooleanField(),
    )
).filter(is_inactive_note=False)
👤Todor

Leave a comment