Reputation: 30111
Just came across this in the django docs
Calling none() will create a queryset that never returns any objects and no query will be executed when accessing the results. A qs.none() queryset is an instance of EmptyQuerySet.
I build a lot of CRUD apps (surprise) and I can't think of a situation where I would need to use none()
.
Why would one want to return an EmptyQuerySet?
Upvotes: 44
Views: 34783
Reputation: 459
In Django Rest Framework (DRF), setting queryset = MyModel.objects.none()
at the class level in DRF (Django Rest Framework) viewsets is a common practice when you override the get_queryset()
method. This approach ensures that the default queryset at the class level does not expose data unintentionally before the get_queryset()
method is invoked.
Here's an example:
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.none() # Default to none for safety
serializer_class = MyModelSerializer
def get_queryset(self):
user = self.request.user
return MyModel.objects.filter(created_by=user) # Customize to filter by entities belonging to authenticated user
This makes your viewset less prone to data leak by design, only fetching data specifically scoped by your custom logic in get_queryset()
.
Upvotes: 0
Reputation: 31
In a multi-tenant application where, for example, PrivateResource
has a foreign key to CurrentTenant
, you don't want to expose the full queryset of PrivateResource
. Instead, write a custom manager to filter by current_tenant
. However, if current tenant is undetermined for some reason, it is safest to return an empty queryset for the PrivateResource
, so no private data is exposed.
Upvotes: 0
Reputation: 1
none() is used in get_queryset() to return an empty queryset depending on the state of has_view_or_change_permission() as shown below:
class BaseModelAdmin(metaclass=forms.MediaDefiningClass):
# ...
def has_view_or_change_permission(self, request, obj=None):
return self.has_view_permission(request, obj) or self.has_change_permission(
request, obj
)
# ...
class InlineModelAdmin(BaseModelAdmin):
# ...
def get_queryset(self, request):
queryset = super().get_queryset(request)
if not self.has_view_or_change_permission(request):
queryset = queryset.none() # Here
return queryset
Upvotes: 0
Reputation: 3467
In cases where you want to append to querysets but want an empty one to begin with Similar to conditions where we instantiate an empty list to begin with but gradually keep appending meaningful values to it example..
def get_me_queryset(conditionA, conditionB, conditionC):
queryset = Model.objects.none()
if conditionA:
queryset |= some_complex_computation(conditionA)
elif conditionB:
queryset |= some_complex_computation(conditionB)
if conditionC:
queryset |= some_simple_computation(conditionC)
return queryset
get_me_queryset
should almost always return instance of django.db.models.query.QuerySet
(because good programming) and not None
or []
, or else it will introduce headaches later..
This way even if none of the conditions come True
, your code will still remain intact. No more type checking
For those who do not undestand |
operator's usage here:
queryset |= queryset2
It translates to:
queryset = queryset + queryset
Upvotes: 23
Reputation: 15371
Another good use case for this is if some calling method wants to call .values_list()
or similar on results. If the method returned None, you'd get an error like
AttributeError: 'list' object has no attribute 'values_list'
But if your clause returns MyModel.objects.none()
instead of None
, the calling code will be happy, since the returned data is an empty queryset rather than a None object.
Another way of putting it is that it allows you to not mix up return types (like "this function returns a QuerySet or None," which is messy).
Upvotes: 2
Reputation: 2509
It's useful to see where qs.none()
is used in other examples in the Django docs. For example, when initializing a model formset using a queryset if you want the resulting formset to be empty the example given is:
formset = AuthorFormSet(queryset=Author.objects.none())
Upvotes: 1
Reputation: 306
another use of queryset.none is when you don't know if there will be objects but do not want to raise an error.
example:
class DummyMixin(object):
def get_context_data(self,**kwargs):
""" Return all the pks of objects into the context """
context = super(DummyMixin, self).get_context_data(**kwargs)
objects_pks = context.get(
"object_list",
Mymodel.objects.none()
).values_list("pk", flat=True)
context["objects_pks"] = objects_pks
Upvotes: 3
Reputation: 2958
Usually in instances where you need to provide a QuerySet
, but there isn't one to provide - such as calling a method or to give to a template.
The advantage is if you know there is going to be no result (or don't want a result) and you still need one, none()
will not hit the database.
For a non-realistic example, say you have an API where you can query your permissions. If the account hasn't been confirmed, since you already have the Account
object and you can see that account.is_activated
is False
, you could skip checking the database for permissions by just using Permission.objects.none()
Upvotes: 45