python - Django 对象存在

标签 python django django-models

我想检查数据库中是否存在该对象,如果不存在,则将其添加到数据库中。 我试过了:

if not MyModel.objects().get(surname='foo'): 
     management.call_command('loaddata', 'Bootstrap_data', verbosity=0)#adds this object from fixtures

但是我从 db(sqlite3) 得到一个查询错误。这种对象校验方式如何解决?

错误是:

DoesNotExist at /
MyModel matching query does not exist.

因为数据库中没有这个姓氏的对象。

最佳答案

通常您会使用 get_or_create .

model_instance = MyModel.objects.get_or_create(surname='foo')

你真的不应该为这样的事情使用 management.call_command

就是说,如果我误解了你有充分的理由,试试这个:

try:
    MyModel.objects.get(surname='foo')
except MyModel.DoesNotExist:
      management.call_command(....)

if not MyModel.objects.filter(surname='foo').exists():
      management.call_command(....)

关于python - Django 对象存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8761981/

相关文章:

python - Mac 上的 TensorFlow 安装错误

python - “元组”对象在更新图像对象时没有属性 '_committed' 错误?

python - Django:具有与客户端关联的唯一分机号,但与另一个客户端关联的相同分机号

python - 如何在django中找到与另一个对象没有关系的对象列表

python - 如何通过附加配置自动调度

python - 无法加载插件 Nose 计时器

python - matplotlib 中的 Pandas 自动日期时间格式

python - 鹡鸰安装 : Wagtail command not found

python - 如何使用 django 在 Python 中编写一个简单的服务器推送实现?

python - 在 Django 模型中的一个变量中存储多个信息