检查数据是否存在于django中的最佳方法是什么? [英] What is the best way to check if data is present in django?

查看:139
本文介绍了检查数据是否存在于django中的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using django, which is the "way" to check if data is present?

我知道我可以在尝试中获得try / catch块,或者在过滤器上检查 len 的大小

I know i can either have a try/catch block on a get, or check the size of a len on a filter

ie

try:
    DemoModel.objects.get(id=8)
catch DoesNotExist:
    catch stuff here

if not len(DemoModel.objects.filter(id=8):
    do stuff here

我想我'将最佳定义为

a。标准方式
b。更有效的方式

a. the standard way b. the more efficient way

还是没有真正的区别?还是没有党派的第三种方式?

or is there no real difference? Or is there a non-partisan third way?

推荐答案

如果您需要使用

try:
    object = DemoModel.objects.get(id=8)
    #use object here
catch DoesNotExist:
    #catch stuff here

如果不需要,请使用exis ts()。

If you don't need to, just use exists().

if DemoModel.objects.filter(id=8).exists():
    #do stuff here

这篇关于检查数据是否存在于django中的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆