Reputation: 507
I'm reading someone's code, and there is written
get_object_or_404(Order, id=-1)
Could someone explain the purpose of id=-1
?
Upvotes: 1
Views: 494
Reputation: 476574
Well get_object_or_404
[Django-doc] takes as input a model or queryset, and aims to filter it with the remaining positional and named parameters. It then aims to fetch that object, and raises a 404 in case the object does not exists.
Here we thus aim to obtain an Order
object with id=-1
. So the query that is executed "behind the curtains" is:
Order.objects.get(id=-1) # SELECT order.* FROM order WHERE id=-1
In most databases id
s are however (strictly) positive (if these are assigned automatically). So unless an Order
object is explicitly saved with id=-1
, this will always raise a 404 exception.
Sometimes however one stores objects with negative id to make it easy to retrieve and update "special" ones (although personally I think it is not a good practice, since this actually is related to the singleton and global state anti-patterns). You thus can look (for example in the database, or in the code) if there are objects with negative id
s. If these objects are not created, then this code will always result in a 404 response.
Upvotes: 2