1105π
You could do this:
Name.objects.exclude(alias__isnull=True)
If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:
Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')
Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias
is either null or an empty string, so you get all Name
objects that have a not-null, not-empty alias
field. The generated SQL would look something like:
SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""
You can also pass multiple arguments to a single call to exclude
, which would ensure that only objects that meet every condition get excluded:
Name.objects.exclude(some_field=True, other_field=True)
Here, rows in which some_field
and other_field
are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:
SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)
Alternatively, if your logic is more complex than that, you could use Djangoβs Q objects:
from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))
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.
- [Django]-Get user profile in django
- [Django]-Django: Open uploaded file while still in memory; In the Form Clean method?
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
41π
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.
- [Django]-What does on_delete do on Django models?
- [Django]-How to pass information using an HTTP redirect (in Django)
- [Django]-Django: show the count of related objects in admin list_display
9π
If you want to exclude null (None
), empty string (""
), as well as a string containing white spaces (" "
), you can use the __regex
along with __isnull
filter option
Name.objects.filter(
alias__isnull = False,
alias__regex = r"\S+"
)
alias__isnull=False
excludes all the columns null columns
aliax__regex = r"\S+"
makes sure that the column value contains at least one or more non whitespace characters.
- [Django]-Django-way for building a "News Feed" / "Status update" / "Activity Stream"
- [Django]-Using django-rest-interface
- [Django]-Django AutoField with primary_key vs default pk
8π
1. When using exclude, keep the following in mind to avoid common mistakes:
Should not add multiple conditions into an exclude()
block like filter()
. To exclude multiple conditions, you should use multiple exclude()
.
Example: (NOT a AND NOT b)
Entry.objects.exclude(title='').exclude(headline='')
equal to
SELECT... WHERE NOT title = '' AND NOT headline = ''
======================================================
2. Only use multiple when you really know about it:
Example: NOT (a AND b)
Entry.objects.exclude(title='', headline='')
equal to
SELECT.. WHERE NOT (title = '' AND headline = '')
- [Django]-How can I access environment variables directly in a Django template?
- [Django]-Laravel's dd() equivalent in django
- [Django]-The QuerySet value for an exact lookup must be limited to one result using slicing. Filter error
5π
From Django 1.8,
from django.db.models.functions import Length
Name.objects.annotate(alias_length=Length('alias')).filter(alias_length__gt=0)
- [Django]-Django edit user profile
- [Django]-Django + Ajax
- [Django]-Copy a database column into another in Django
4π
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
.
- [Django]-Django admin TabularInline β is there a good way of adding a custom html column?
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Do I need Nginx with Gunicorn if I am not serving any static content?
3π
Another approach using a generic isempty
lookup, that can be used with any field.
It can also be used by django rest_framework or other apps that use django lookups:
from distutils.util import strtobool
from django.db.models import Field
from django.db.models.lookups import BuiltinLookup
@Field.register_lookup
class IsEmpty(BuiltinLookup):
lookup_name = 'isempty'
prepare_rhs = False
def as_sql(self, compiler, connection):
sql, params = compiler.compile(self.lhs)
condition = self.rhs if isinstance(self.rhs, bool) else bool(strtobool(self.rhs))
if condition:
return "%s IS NULL or %s = ''" % (sql, sql), params
else:
return "%s <> ''" % sql, params
You can then use it like this:
Name.objects.filter(alias__isempty=False)
- [Django]-Django 2 β How to register a user using email confirmation and CBVs?
- [Django]-Django Sitemaps and "normal" views
- [Django]-Many-To-Many Fields View on Django Admin
- [Django]-Why is __init__ module in django project loaded twice
- [Django]-How does one make logging color in Django/Google App Engine?
- [Django]-Django: using more than one database with inspectdb?