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)
- [Django]-Django get query execution time
- [Django]-Django check_password() always returning False
- [Django]-Django ORM to find if a string contains column value
- [Django]-Django is terribly slow on Mac OS X Lion
- [Django]-Can you use a Django form multiple times in one view?
Source:stackexchange.com