我在post_save函数中有以下代码
@receiver(post_save)
def update_parent_location(sender, instance=None, created=False, **kwargs):
list_of_models = ('A', 'B', 'C')
if sender.__name__ in list_of_models:
groups = instance.group_set.all()
fields_to_update = tuple(field.lower() for field in list_of_models)
for field in fields_to_update:
parent = getattr(instance, field, None)
if parent is not None:
parent.groups.add(*groups)
parent.save()
我怎么知道
parent.groups.add(*groups)
部分实际上是添加了一个新对象还是静默失败了?
答案 0 :(得分:1)
您可以查询之前和之后的组计数,以查看是否有任何更改:
...
num_groups = parent.groups.count()
parent.groups.add(*groups)
if parent.groups.count() > num_groups:
# Something was added
parent.save()
...