Django:添加之前检查对象是否已存在 [英] Django: check whether an object already exists before adding
问题描述
这是一个非常简单的Django问题,尽管有很多猎头,但我在Django文档中找不到答案!
This is a pretty simple Django question, but I can't find the answer in the Django docs, despite lots of hunting!
如何检查是否存在对象已经存在,并且仅当它不已经存在时才添加它?
How do I check whether an object already exists, and only add it if it does not already exist?
这是代码-我不想添加follow_role数据库中两次(如果已经存在)。我如何首先检查?也许使用get()-但是Django会抱怨get()没有返回任何东西吗?
Here's the code - I don't want to add the follow_role twice in the database if it already exists. How do I check first? Use get() maybe - but then will Django complain if get() doesn't return anything?
current_user = request.user
follow_role = UserToUserRole(from_user=current_user, to_user=user, role='follow')
follow_role.save()
谢谢!
推荐答案
此惯用法有一个帮助函数,称为 get_or_create模型管理员:
There's a helper function for this idiom called 'get_or_create' on your model manager:
role, created = UserToUserRole.objects.get_or_create(
from_user=current_user, to_user=user, role='follow')
它返回(model,bool)的元组,其中'model'是您感兴趣的对象,'bool'告诉您是否必须创建它。
It returns a tuple of (model, bool) where 'model' is the object you're interested in and 'bool' tells you whether it had to be created or not.
这篇关于Django:添加之前检查对象是否已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!