m2m 字段上的 post_save 信号
我有一个非常通用的文章模型,与标签模型有 m2m 关系。 我想记录每个标签的使用情况,我认为最好的方法是对标签模型上的计数字段进行非规范化,并在每次保存文章时更新它。 我怎样才能做到这一点,或者也许有更好的方法?
I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 Django 1.2 中的新功能:
http://docs.djangoproject.com/en/dev/ref /信号/#m2m-更改
This is a new feature in Django 1.2:
http://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed
您可以通过创建 M2M 关系的中间模型,并将其用作
post_save
和post_delete
信号的挂钩,以更新中的非规范化列文章
表。例如,我对 soclone 中收藏的
问题
计数执行此操作,其中用户
与问题
有M2M关系:django开发者邮件列表上有一些关于实现一种以声明方式声明非规范化的方法以避免编写像上面这样的代码:
You can do this by creating an intermediate model for the M2M relationship and use it as your hook for the
post_save
andpost_delete
signals to update the denormalised column in theArticle
table.For example, I do this for favourited
Question
counts in soclone, whereUser
s have a M2M relationship withQuestion
s:There's been a bit of discussion on the django-developers mailing list about implementing a means of declaratively declaring denormalisations to avoid having to write code like the above: