I want to filter Django queryset by the same field multiple times using Q
to include/exclude records with specific value in this field.
I'll use sample model to illustrate my case. Say I have a Record
model with field status
. This field can be one of three states A
, B
, C
.
class Record(models.Model):
STATUS_A = 'A'
STATUS_B = 'B'
STATUS_C = 'C'
SOME_STATUSES = (
(STATUS_A, 'Something A'),
(STATUS_B, 'Something B'),
(STATUS_C, 'Something C'),
)
status = models.CharField(
max_length=1,
choices= SOME_STATUSES,
default= STATUS_A,
)
I have a DRF ViewSet
that's responsible for returning filtered queryset of Record
objects.
Right now I'm filtering query set by a single status, so my URL
looks something like:
.../?status=A
.../?status=B
.../?status=C
But say I want to filter queryset by multiple statuses:
Return all records with status A
and B
.
Or instead I want to return all the records except those with status C
. I'm not sure how to build URL in those cases. I know that duplicating parameters in URL is a very bad practice:
.../?status=A&status=B
How does one request A
AND
B
or NOT
C
?
The remaining part of the question how to handle those multiple values is unclear probably because I don't understand how to build such a query in the first place.