【问题标题】:Django overwrite model save method to check if a many to many field has changedDjango覆盖模型保存方法以检查多对多字段是否已更改
【发布时间】:2021-11-11 14:39:18
【问题描述】:

所以我有一个模型,我需要覆盖其保存属性以检查多对多关系是否已更改。通常,对于 char 字段,您可以执行以下操作,但对于很多人来说,它的工作方式不同。

class Interest(TimestampedModel):
    subjects = models.ManyToManyField('genre.Subject', blank=True)

    def save(self, *args, **kwargs):
        if self.id:
            old_subjects = Interest.objects.filter(pk=self.pk).first().subjects.all()
            subjects = self.subjects.all()
            if subjects != old_subjects:
                # Do stuff

知道如何为多对多领域制作这样的东西吗?

【问题讨论】:

    标签: python django model


    【解决方案1】:

    信号怎么样?查看m2m_changed 信号文档here

    你可以像这样使用它:

    from django.db.models.signals import m2m_changed
    
    @receiver(m2m_changed, sender=Interest.subjects.through)
    def video_category_changed(sender, instance, **kwargs):
    
        # do stuff to the Interest instance:
        instance...
    

    【讨论】:

    • 这很有帮助,它确实给了我一个好的开始,但这并不是我正在寻找的答案。我的不好是描述性不够。如何扩展它来检查“old_subjects”和“new_subjects”变量,就像我的例子一样。在 m2m 更改为我想要执行的操作后,我需要同时访问旧主题和新主题。
    • pre_addpost_addpre_removepost_remove kwargs - 我以前没有使用过它们,但是根据文档,看来你可以使用这些来解决你的问题问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 2019-10-24
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多