Django 管理员保存不使用 m2m_changed 信号发送 post_remove 操作

标签 django m2m

当我保存相关模型时,我试图让多对多模型进行更新。这应该可以使用 m2m_changed signal (它有效!但不在管理员中?)例如

# i want the references field to update when related model is saved.
# so just call count_references

class Tag(models.Model):
    """Group everything into categories"""
    # stuff stuff stuff
    references = models.IntegerField(default=0, editable=False)

    def count_references(self):
        # just add up references each time to save headaches
        self.references = 0
        # search for reverse managers
        sets = re.compile('^\w+_set$')
        for rel_set in [method for method in dir(self) if sets.match(method)]:
            self.references += getattr(self, rel_set).count()
        self.save()

class Entry(models.Model):
    """Blog entry"""
    # stuff stuff stuff
    tags = models.ManyToManyField('Tag', blank=True)

# this will call count_references when entry adds or removes tags

@receiver(m2m_changed, sender=Entry.tags.through)
def update_tag_ref_count(sender, instance, action, reverse, model, pk_set, **kwargs):
    print action
    if not reverse and action == 'post_add' or action == 'post_remove':
        for tag_pk in pk_set:
            print tag_pk
            Tag.objects.get(pk=tag_pk).count_references()
            print Tag.objects.get(pk=tag_pk).references

在 shell 中运行时,一切正常。例如像这样的tests.py:
t = Tag.objects.all()[0]
s = Snippet.objects.all()[0]

s.tags.remove(t)
s.save()

s.tags.add(t)
s.save()

我得到以下信息(其中 'test' 是正在打印的标签名称):
pre_remove
post_remove
test
0
pre_add
post_add
test
1

完美的!当我向管理中的条目添加标签时,我得到以下信息(在 HTTP 内容之间):
pre_clear
post_clear
pre_add
post_add
test
1

还好!不确定需要什么 pre/post_clear ......当我删除时:
pre_clear
post_clear

啊!未调用 pre/post_remove! pre/post_clear 既无用又不提供任何主键。这感觉像是管理实现中的一个错误。有什么建议?

更新 :Bug #16073提交并接受。

最佳答案

(将其创建为社区 wiki 以将其作为“未回答”的问题结束。)

这是 Django 中的一个错误。 OP 在 https://code.djangoproject.com/ticket/16073 提交了一张罚单.

关于Django 管理员保存不使用 m2m_changed 信号发送 post_remove 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6092613/

相关文章:

Django IPython sqlite 提示幼稚的日期时间

python - IntegrityError : (1451, '无法删除或更新父行 : a foreign key constraint fails (. 。))

python - 基于另一个 M2M 预填充 Django M2M 字段

Django 在管理页面上显示多对多关系中的更多字段

python - 在 django 中哪里放置自定义验证器?

python - 将 django 应用程序上的 mysql 数据库部署到生产服务器

python - 在 for 循环中合并过滤结果

server - MQTT 服务器如何向客户端发送消息,表示其无权连接?

mysql - 数据库结构 : Would this structure work with this m:m?

python - 创建管理员限制的网址