views:

2759

answers:

2

Hi,

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

+15  A: 

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.

musicfreak
Excellent, this is what I exactly wanted. Thanks.
VN44CA
A: 

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.

b3ng0