gpt4 book ai didi

python - Django 多对多字段复制

转载 作者:太空狗 更新时间:2023-10-30 02:34:40 24 4
gpt4 key购买 nike

我有一个包含 2 个多对多字段的 Django 模型。从管理界面保存模型时,我需要检查第二个字段是否为空,如果为空,则我需要将第一个字段中的项目复制到第二个字段中。我该怎么做?

更新

Matthew 的回答似乎很有效,但在复制该字段后我无法保存实例。我试过 instance.save() 但没有成功。

最佳答案

要使用的信号不是post_save,而是m2m_changed,它在模型保存到数据库后发送。

@models.signals.m2m_changed(sender=MyModel.second_m2m.through)
def duplicate_other_on_this_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
# just before adding a possibly empty set in "second_m2m", check and populate.
if action == 'pre_add' and not pk_set:
instance.__was_empty = True
pk_set.update(instance.first_m2m.values_list('pk', flat=True))

@models.signals.m2m_changed(sender=MyModel.first_m2m.through)
def duplicate_this_on_other_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
# Just in case the "first_m2m" signals are sent after the other
# so the actual "population" of the "second_m2m" is wrong:
if action == 'post_add' and not pk_set and getattr(instance, '__was_empty'):
instance.second_m2m = list(pk_set)
delattr(instance, '__was_empty')

编辑:下一个代码更简单,并且基于模型定义的新知识

在您的代码中,“first_m2m”信号在“second_m2m”之前发送(这实际上取决于您的模型定义)。因此,我们可以假设当接收到“second_m2m”信号时,“first_m2m”已经填充了当前数据。

这让我们更开心,因为现在你只需要检查 m2m-pre-add:

@models.signals.m2m_changed(sender=MyModel.second_m2m.through)
def duplicate_other_on_this_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
# just before adding a possibly empty set in "second_m2m", check and populate.
if action == 'pre_add' and not pk_set:
pk_set.update(instance.first_m2m.values_list('pk', flat=True))

关于python - Django 多对多字段复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6971063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com