Taras
Taras

Reputation: 507

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?

Upvotes: 1

Views: 494

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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 ids 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 ids. If these objects are not created, then this code will always result in a 404 response.

Upvotes: 2

Related Questions