python – Django多对多字段副本
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – Django多对多字段副本,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1734字,纯文字阅读大概需要3分钟。
内容图文
![python – Django多对多字段副本](/upload/InfoBanner/zyjiaocheng/815/48ef770c22784dbea67abedec5483919.jpg)
我有一个Django模型,有2个多对多字段.当我从管理界面保存模型时,我需要检查第二个字段是否为空白,如果它是空白的,那么我需要将第一个现场的项目复制到第二个.我怎样才能做到这一点?
UPDATE
马修的答案看起来似乎很有效但我在复制字段后无法保存实例.我尝试过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多对多字段副本全部内容,希望文章能够帮你解决python – Django多对多字段副本所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。