I have to filter a queryset by a dynamic value (which can be None): may I simply write:
filtered_queryset = queryset.filter(field=value)
or shall I check for None:
if value is None: filtered_queryset = queryset.filter(field__isnull=True) else: filtered_queryset = queryset.filter(field=value)
Does the behaviour depend on the particular DBMS?
In Django queryset we have __isnull to check if a value is null. Here were filtering all the values from MyModel model, which have an alias = Null. exclude allows you to pass multiple arguments, it will the then check for every argument. If your query is still more complex, you can use Django's Q Objects.
Unless you set null=True as well, your database should complain if you tried to enter a blank value. If your foreign key field can take null values, it will return None on null, so to check if it was "left blank", you could simply check if the field is None . What's the difference between is None and if not ?
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With