Django Manytomany信号? [英] Django manytomany signals?
问题描述
假设我有这样的模型
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 ?
推荐答案
如果可能,在您的情况下,您可以引入参与
将加入活动和用户的模型:
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')
并处理由发送的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 Manytomany信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!