Django 多条信号? [英] Django manytomany signals?

查看:29
本文介绍了Django 多条信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的模型

class Event(models.Model)
    users_count = models.IntegerField(default=0)
    users = models.ManyToManyField(User)

如果事件添加/删除一些用户,您建议如何更新 users_count 值?

How would you recommend to update users_count value if Event add/delete some users ?

推荐答案

如果可能的话,你可以引入 Participation 模型来加入事件和用户:

If possible in your case, you could introduce Participation model which would join Event and User:

class Participation(models.Model):
    user = models.ForeignKey(User)
    event = models.ForeignKey(Event)

class Event(models.Model):
    users = models.ManyToManyField(User, through='Participation')

并处理Participation发送的pre_save信号以更新instance.event计数.它将显着简化 m2m 的处理.在大多数情况下,后来证明某些逻辑和数据最适合中间模型.如果您不是这种情况,请尝试自定义解决方案(无论如何,您都不应该有很多代码路径将用户添加到事件).

And handle pre_save signal sent by Participation to update instance.event counts. It would simplify handling of m2m significantly. And in most cases, it turns out later on that some logic and data fits best in the middle model. If that's not your case, try a custom solution (you should not have many code paths adding Users to Events anyway).

这篇关于Django 多条信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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