There are two classes in a model- Task and TaskArchives. i need to create a new task if it does not already exist in both Task andTaskArchives. i've tried checking the DoesNotExist exception with an and clause. but it doesn't work. could someone please suggest a different method ??
模型中有两个类 - Task和TaskArchives。我需要创建一个新任务,如果它在Task和TaskArchives中都不存在。我已经尝试使用和子句检查DoesNotExist异常。但它不起作用。有人可以建议一个不同的方法??
for event in events:
try:
obj = Task.objects.get(task_id = event['id'])
obj_archive = TaskArchive.objects.get(task_id = event['id'])
except Task.DoesNotExist and TaskArchive.DoesNotExist:
obj = Task.objects.create(
task_id = event['id'],
title = event['summary'],
created_by = User.objects.get(email=event['creator']['email']),
status = "upcoming",
due_date = event['start']['dateTime']
)
Thanks in advance, Reenu.
在此先感谢Reenu。
1 个解决方案
#1
2
You can try using the QuerySet's exists()
function. It returns True
if the QuerySet contains any results, and False
if not.
您可以尝试使用QuerySet的exists()函数。如果QuerySet包含任何结果,则返回True,否则返回False。
So, for the example above I would write:
所以,对于上面的例子我会写:
if not Task.objects.filter(task_id = event['id']).exists() and
not TaskArchive.objects.filter(task_id = event['id']).exists:
# no object satisfying query exists
else:
# at least one object satisfying query exists
#1
2
You can try using the QuerySet's exists()
function. It returns True
if the QuerySet contains any results, and False
if not.
您可以尝试使用QuerySet的exists()函数。如果QuerySet包含任何结果,则返回True,否则返回False。
So, for the example above I would write:
所以,对于上面的例子我会写:
if not Task.objects.filter(task_id = event['id']).exists() and
not TaskArchive.objects.filter(task_id = event['id']).exists:
# no object satisfying query exists
else:
# at least one object satisfying query exists