Django filter — How do I go about filtering for empty or NULL names in a queryset?

Up vote 24 down vote favorite 7 share g+ share fb share tw.

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? Thanks, VN44CA django django-models django-queryset filter null link|improve this question edited Dec 2 '11 at 12:15Glycerine2,6602617 asked May 10 '09 at 2:26VN44CA49111121 66% accept rate.

You could do this: Name.objects. Filter(alias__isnull=False) If you absolutely need to check for empty strings, you alternatively could do something like this, although it's more complex and thus slower: from django.db. Models import Q Name.objects.

Exclude(Q(alias__isnull=True) | Q(alias__exact='')) For more info see this page in the Django docs. Edit: As per b3ng0's answer below, the preferred way to model multiple conditions now is to chain together the methods like so: Name.objects. Exclude(alias__isnull=True).

Exclude(alias__exact='') Chaining these methods together basically produces the equivalent of an OR in the SQL code. To get an AND, you can just pass multiple arguments to a single call to exclude: Name.objects. Exclude(some_field=True, other_field=True) Here, only rows in which some_field and other_field are true get excluded.

Excellent, this is what I exactly wanted. Thanks. – VN44CA May 10 '09 at 2:56.

Firstly, the Django docs strongly reccomend not using NULL values for string-based fields such as CharField or TextField. Read the documentation for the explanation. 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.

1 A link to where it says that would have been nice. Docs.djangoproject.com/en/dev/ref/models/fields/#null – Mark Sep 25 '11 at 21:50.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions