Mic*_*ian 2 python django django-queryset django-filter
所以,我正在使用Django update_or_create API来构建我的表单数据.它工作得很好......但是,一旦构建,我需要一种方法来检查实际更新的配置文件或它们是否是第一次创建的?
举个例子:
for people in peoples:
people, updated = People.objects.update_or_create(
id=people.person_id,
defaults={
'first_name': people.first_name,
}
)
Run Code Online (Sandbox Code Playgroud)
过滤查询集:
people = People.objects.filter(
id__in=whatever,
)
Run Code Online (Sandbox Code Playgroud)
但是,现在,我正在尝试通过创建或更新来过滤查询集...但是没有看到它的API(例如,各种各样的拟合)
所以,我想做的事情如下:
updated = Person.objects.filter(updated=True, created_for_first_time=False)
and then I can write something like
if updated:
do this
else:
do this
Run Code Online (Sandbox Code Playgroud)
基本上,我只想检查配置文件是否第一次更新或创建.
正如您在问题中所示,该update_or_create方法返回一个元组(obj, created),obj在对象中,并且created是一个布尔值,显示是否创建了一个新对象.
您可以检查布尔字段的值,并创建一个列表来存储新创建的对象的ID
new_objects = []
for people in peoples:
obj, created = People.objects.update_or_create(...)
if created:
new_objects.append(obj.id)
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用该列表进行过滤:
new_people = People.objects.filter(id__in=new_objects)
existing_people = People.objects.exclude(id__in=new_objects)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7418 次 |
| 最近记录: |