Django创建或更新获取更改字段

2024-10-01 11:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Djangocreate_or_update函数

在更新的情况下,是否有方法知道已更改字段的列表

显然,我可以在之前和之后使用get_or_create函数来更新模型。。但我正在寻找一种方法,通过一个查询就可以实现这一点

可能吗


Tags: or方法函数模型列表getcreate情况
2条回答

更新或创建(默认值=无,**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来识别实例:

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)

此时的差异字段列表应仅包含第一个\u名称

相关问题 更多 >