Django:无法使用 m2m_changed 信号检测多对多字段的变化 - 在模型级审计 [英] Django: cannot detect changes on many-to-many field with m2m_changed signal - auditing at model-level

查看:28
本文介绍了Django:无法使用 m2m_changed 信号检测多对多字段的变化 - 在模型级审计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想跟踪任何模型上的哪些字段发生了变化(即在模型级别进行审计,因为它更具原子性,而不是像 django 和 django-reversion 已经可以做到的那样在管理/表单级别).我可以使用前/后保存/删除信号对任何字段执行此操作.但是,我在 m2m 场上这样做时遇到了问题.

I'd like to keep track on what field has changed on any model (i.e. audit at model level since it's more atomic, not at admin/form-level like what django and django-reversion can already do). I'm able to do that for any field using pre/post save/delete signals. However, I have a problem of doing that on an m2m field.

对于下面的代码示例,我在用户更改表单中定义了custom_groups"m2m 字段,因为它是反向关系.例如,当用户在管理界面上保存表单时,我想记录custom_groups"字段是否发生变化.

For the code sample below, i define 'custom_groups' m2m field in user change form since it's a reverse relation. When user saves the form on admin interface for example, I'd like to log if there's a change in 'custom_groups' field.

型号:

from django.contrib.auth.models import User

class CustomGroup(models.Model):
    users = models.ManyToManyField(User, related_name='custom_groups')

模型表格:

class CustomUserChangeForm(UserChangeForm):
    custom_groups = forms.ModelMultipleChoiceField(required=False, queryset=CustomGroup.objects.all())

使用 m2m_changed 信号的问题在于,对于使用赋值运算符更新 m2m 字段的情况,我无法检查实际发生了什么变化:

The problem with using m2m_changed signal is that i can't check what has actually changed for the case where the m2m field is updated using assignment operator:

user.custom_groups = self.cleaned_data['custom_groups']

这是因为在手动添加所有对象之前,django 会在内部对 *custom_groups* 执行 clear().这将执行 pre/post-clear,然后在 m2m 字段上执行 pre/post save.

This is because internally django will perform a clear() on *custom_groups*, before manually adding all objects. This will execute pre/post-clear and then pre/post save on the m2m field.

我是否以错误的方式做这一切?有没有更简单可行的方法?

Am I doing all this the wrong way? Is there a simpler method that can actually work?

谢谢!

推荐答案

我遇到了类似的问题,我想我可以解决它.我不知道你是如何使用 m2m_changed 但它应该在 models.py 上并且应该类似于这样的:

I had a similar problem and I think I could solve it. I don't know how you are using the m2m_changed but it should be on models.py and should be similar to something like this:

signals.m2m_changed.connect(your_function, sender=CustomGroup.users.through)

现在,我将创建一个包含该函数的signals.py 文件,下面的代码应该会打印出您选择的选项:

Now, I would create a signals.py file containing that function, and the following code should print you the options that you have selected:

def your_function(sender, instance, action, reverse, model, pk_set, **kwargs):
    if action == 'post_add':
        for val in pk_set:
            print val

现在,您知道更新的值了.我希望这可以解决您的问题.

Now, you know the updated values. I hope this could solve your problem.

这篇关于Django:无法使用 m2m_changed 信号检测多对多字段的变化 - 在模型级审计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆