filter with different operator in django
To filter with different operators in Django, you can use the filter()
method along with different lookup operators. Here are the steps with explanations for each:
Exact match (
exact
): Use__exact
to match exact values in a field.python ModelName.objects.filter(field_name__exact=value)
Case-insensitive exact match (
iexact
): Use__iexact
to perform a case-insensitive exact match.python ModelName.objects.filter(field_name__iexact=value)
Contains (
contains
): Use__contains
to find records containing a specific value.python ModelName.objects.filter(field_name__contains=value)
Case-insensitive contains (
icontains
): Use__icontains
for a case-insensitive 'contains' search.python ModelName.objects.filter(field_name__icontains=value)
Starts with (
startswith
): Use__startswith
to filter records starting with a specific value.python ModelName.objects.filter(field_name__startswith=value)
Ends with (
endswith
): Use__endswith
to filter records ending with a specific value.python ModelName.objects.filter(field_name__endswith=value)
Greater than (
gt
), Less than (lt
), Greater than or equal to (gte
), Less than or equal to (lte
): Use__gt
,__lt
,__gte
, and__lte
for numerical or date-based comparisons.python ModelName.objects.filter(field_name__gt=value) ModelName.objects.filter(field_name__lt=value) ModelName.objects.filter(field_name__gte=value) ModelName.objects.filter(field_name__lte=value)
In a list of values (
in
): Use__in
to filter records where the field value is in a list of values.python ModelName.objects.filter(field_name__in=[value1, value2, ...])
Not in a list of values (
notin
orexclude
): Use~Q(field_name__in=[value1, value2, ...])
orexclude()
to filter records where the field value is not in a list of values.python ModelName.objects.filter(~Q(field_name__in=[value1, value2, ...])) ModelName.objects.exclude(field_name__in=[value1, value2, ...])
These examples cover various filtering options in Django using different lookup operators to customize your queries based on specific criteria.