检查django中是否存在数据的最佳方法是什么?

bha*_*ral 3 django

使用django,这是检查数据是否存在的"方法"?

我知道我可以在get上有一个try/catch块,或者检查len过滤器上的a 的大小

try:
    DemoModel.objects.get(id=8)
catch DoesNotExist:
    catch stuff here
Run Code Online (Sandbox Code Playgroud)

要么

if not len(DemoModel.objects.filter(id=8):
    do stuff here
Run Code Online (Sandbox Code Playgroud)

我想我将"最佳"定义为

一个.标准方式b.更有效的方式

或者没有真正的区别?或者是否存在无党派的第三种方式?

dan*_*roa 7

如果需要使用该对象,请使用try/catch.

try:
    object = DemoModel.objects.get(id=8)
    #use object here
catch DoesNotExist:
    #catch stuff here
Run Code Online (Sandbox Code Playgroud)

如果您不需要,只需使用exists().

if DemoModel.objects.filter(id=8).exists():
    #do stuff here
Run Code Online (Sandbox Code Playgroud)