python - How to exclude results with get_object_or_404? -
In Django, you can create a SQL like not equal
. An example might be.
Model.objects.exclude (condition = 'deleted')
Now it works great and the exclusion is very flexible. Since I am a bit lazy, I want to get that functionality when using the get_object_or_404
, but I have not found any way to do this, because you have get_object_or_404
.
What do I have to do, something like this:
model = get_object_or_404 (pk = id, status__exclude = 'deleted')
< P> But unfortunately this does not work because there is no excluded query filter or similar. The best I've come up with so far is doing something like this: object = get_object_or_404 (pk = id) if object.status == 'deleted': return HttpResponseNotfound ('text ')
By doing something, actually defeats the point of using get_object_or_404
, because it is no longer easy one-liner.
Alternatively, I can do this:
object = get_object_or_404 (pk = id, status__in = ['list', 'of', 'items'])
But this will not be very satisfying because I need to keep the list up to date.
I am thinking that I am missing some tricks or feature in Danjang get_object_or_404
to get the desired results?
Use:
from Django.db.models import Model = get_object_or_404 (MyModel, ~ Q (condition = 'destroyed'), pk = id)
Q objects do not allow you to ( ~
operator) and OR (with |
operator)
Note that the Q object should be preceded by pk = id
, because the keyword agreements are finalized in Python Have to come from.
Comments
Post a Comment