31π
β
The ORM will handle None
(cast it to NULL) for you and return a QuerySet
object, so unless you need to catch None
input the first example is fine.
>>> User.objects.filter(username=None)
[]
>>> type(_)
<class 'django.db.models.query.QuerySet'>
>>> str(User.objects.filter(username=None).query)
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" IS NULL
6π
I prefer the second solution which is handled better
Update
if value is None:
filtered_queryset = queryset.filter(field__isnull=True)
# Do some proessing with filtered_queryset object with None values
else:
filtered_queryset = queryset.filter(field=value)
# Do some proessing with filtered_queryset object with not NULL values
Query set can handle Null values..Based on this User.objects.filter(username=None)
this would fetch only values where username=NULL
π€Rajeev
- [Django]-Add data to ModelForm object before saving
- [Django]-Auto-create primary key used when not defining a primary key type warning in Django
- [Django]-How to set a Django model field's default value to a function call / callable (e.g., a date relative to the time of model object creation)
Source:stackexchange.com