如何使用 Django ORM 删除 ID 最低的行?

How to delete row with the lowest id using Django ORM?

我想知道 Django 的等价物是什么:

DELETE FROM article WHERE ID = ( SELECT Min( ID ) FROM article )

我试过的是检索id最低的文章

article = Article.objects.all().order_by("-id")[:1]

然后:

Article.objects.filter(id=article.id).delete()

但我想知道是否还有更多 efficient/elegant 方法可以做到这一点?

无法在单个查询中执行此操作,因为 Django 自行管理某些关系。如果你执行删除,它会先获取你打算删除的项目,然后检查是否需要执行某些触发器,然后删除需要删除的相关对象和对象本身。

因此您可以执行以下操作:

Model.objects.filter(
    pk=Model.objects.annotate(min=Min('pk')
).values('min')[:1]).delete()

但还是会导致多次查询

可能最优雅的方法是:

article = Article.objects.order_by('id').first()
if article:
    article.delete()

根据 django 文档:

first() Returns the first object matched by the queryset, or None if there is no matching object. If the QuerySet has no ordering defined, then the queryset is automatically ordered by the primary key.

你可以使用这个命令:

Article.objects.all().first().delete() if Article.objects.all().first() else None