I have first_name
, last_name
& alias
(optional) which I need to search for. So, I need a query to give me all the names that have an alias set.
Only if I could do:
Name.objects.filter(alias!="")
So, what is the equivalent to the above?
This question is related to
django
django-models
django-queryset
filter
null
Firstly, the Django docs strongly recommend not using NULL values for string-based fields such as CharField or TextField. Read the documentation for the explanation:
https://docs.djangoproject.com/en/dev/ref/models/fields/#null
Solution: You can also chain together methods on QuerySets, I think. Try this:
Name.objects.exclude(alias__isnull=True).exclude(alias="")
That should give you the set you're looking for.
this is another simple way to do it .
Name.objects.exclude(alias=None)
You can simply do this:
Name.objects.exclude(alias="").exclude(alias=None)
It's really just that simple. filter
is used to match and exclude
is to match everything but what it specifies. This would evaluate into SQL as NOT alias='' AND alias IS NOT NULL
.
To avoid common mistakes when using exclude
, remember:
You can not add multiple conditions into an exclude() block like filter
.
To exclude multiple conditions, you must use multiple exclude()
Example
Incorrect:
User.objects.filter(email='[email protected]').exclude(profile__nick_name='', profile__avt='')
Correct:
User.objects.filter(email='[email protected]').exclude(profile__nick_name='').exclude(profile__avt='')
From Django 1.8,
from django.db.models.functions import Length
Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)
Name.objects.filter(alias__gt='',alias__isnull=False)
Source: Stackoverflow.com