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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could do this:
If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:
Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where
aliasis either null or an empty string, so you get allNameobjects that have a not-null, not-emptyaliasfield. The generated SQL would look something like:You can also pass multiple arguments to a single call to
exclude, which would ensure that only objects that meet every condition get excluded:Here, rows in which
some_fieldandother_fieldare true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:Alternatively, if your logic is more complex than that, you could use Django’s Q objects:
For more info see this page and this page in the Django docs.
As an aside: My SQL examples are just an analogy–the actual generated SQL code will probably look different. You’ll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.