Django 多对多字段复制

Con*_*ode 5 python django many-to-many django-models

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

更新

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

rew*_*ten 4

要使用的信号不是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')
Run Code Online (Sandbox Code Playgroud)

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

在您的代码中,“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))
Run Code Online (Sandbox Code Playgroud)