What does it mean when written id=-1 in django request?
What does it mean when written id=-1 in django request?
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
?
id=-1
Order
id=-1
found out, it was a predefined item, like a template...need to load from fixtures.
– petriichuk
Sep 9 '18 at 9:19
1 Answer
1
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.
get_object_or_404
Here we thus aim to obtain an Order
object with id=-1
. So the query that is executed "behind the curtains" is:
Order
id=-1
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.
id
Order
id=-1
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.
id
found out, it was a predefined item, like a template...need to load from fixtures.
– petriichuk
Sep 9 '18 at 9:19
@petriichuk: yes, that was the hypothesis I have put forward in the last paragraph :)
– Willem Van Onsem
Sep 9 '18 at 9:21
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It aims to fetch an
Order
object withid=-1
, and if that fails, it will raise a 404 error. Since in most databases, integers are (strictly) positive, this will probably always fail– Willem Van Onsem
Sep 9 '18 at 9:04