old_instance = Person.objects.filter(first_name=first_name, last_name=last_name)
old_instance = old_instance[0] if old_instance else None
new_instance, created = Person.objects.update_or_create(
first_name=first_name, last_name=last_name,
defaults={'first_name': 'Bob'},
)
# it's been updated and we have the old instance
if not created and old_instance:
# get a list of the model's fields
fields = Person._meta.get_all_field_names()
# compute the fields which have changed
diff_fields = filter(lambda field: getattr(old_instance,field,None)!=getattr(new_instance,field,None), fields)
更新或创建(默认值=无,**kwargs)
update_或create方法尝试根据给定的KWARG从数据库中获取对象。如果找到匹配项,将更新在默认字典中传递的字段。
查询不关心更新的字段是否已更改,“default”中的所有字段都已更新
返回(object,created)的元组,其中object是已创建或更新的对象,created是指定是否创建新对象的布尔值
https://docs.djangoproject.com/en/3.0/ref/models/querysets/#update-or-create
也许这不是最好的解决方案,但我认为它能完成任务。您可以检索将被更新的实例,然后使用filter()和lambda函数计算已更改的字段,正如Rahul Gupta在thisanswer中所建议的那样
假设您可以通过docs中报告的first_name和last_name来识别实例:
此时的差异字段列表应仅包含第一个\u名称
相关问题 更多 >
编程相关推荐