Home > Enterprise >  Is it safe to delete a Django QuerySet that may be empty?
Is it safe to delete a Django QuerySet that may be empty?

Time:12-30

Is it safe to attempt to delete a QuerySet that might be empty? In other words, if I am not sure if the name "MJ" exists, is there any functional difference between these 2 approaches? Is either preferred?

1)

query = m.objects.filter(name="MJ")
if query.exists():
    query.get().delete()
m.objects.filter(name="MJ").delete()

CodePudding user response:

Yes. The .get() will try to retrieve a single object, and it will raise an error if there are multiple such objects.

Furthermore if there is only one record, the first variant will make three queries: first check if there exists at least one record, then fetch that record, and then finally make a delete call, which can also result in delete triggers.

The second will delete fetch the primary keys of the objects it will remove, run delete triggers and finally remove these objects. It is thus more efficient. Furthermore if no such record exists, or multiple objects with MJ as name, it will remove these objects, so it is less error prone and more efficient.

  • Related