模型“行为”在姜戈中
我是 Django 新手,从 PHP 迁移到 Propel ORM 引擎。 这就是我目前在 Django 中所做的事情。我的网站有几个模型,比如
- Book,
- Publisher,
- Comment,
- Article等等(这不是重点)
每个模型都可以 用户喜欢或不喜欢(仅一次)将模型的评级更改为+1或-1。
就 PHP 而言,我会创建一个行为,例如。 “Rateable”,它将向原始模型和查询类添加一些字段和方法(例如 get_ rating()
、order_by_ rating()
等),并为每个字段和方法创建一个单独的表模型,例如book_ rating_history
将保存每个对象的所有评级,以确定用户是否可以或不能更改评级(或在必要时显示所有对象的评级)。因此,我需要做的就是在模型声明中指定“Rateable”行为,仅此而已。其他一切都是自动完成的。
问题是 - 如何在 Django 中解决这个问题?如何正确建模?在类似的情况下您会使用哪些技术?
I'm new to Django, moved from PHP with Propel ORM engine.
So here is what I am currently doing in Django. My website has several models like
- Book,
- Publisher,
- Comment,
- Article and so on (it's not the point)
Each of them can can be
liked or disliked by a user (only once) changing the model's rating by +1 or -1.
In terms of PHP i would create a behavior, for ex. "Rateable" which would add some fields and methods to the original model and query class (like get_rating()
, order_by_rating()
, etc) and create a separate table for each model, for ex. book_rating_history
which would hold all of the ratings for each object, to determine if the user can or can't change the rating (or show all object's ratings, if necessary). So all I would need to do is to specify the "Rateable" behavior in the model declaration, and that's all. Everything else is done automatically.
The question is - how to solve this in Django? How to model correctly? Which techniques do you use in similar cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要单独存储评级和书籍,就像这样(未经测试)。
unique_together
强制执行每个用户只能对给定的书籍评分一次。然后,您可以使用以下内容:
如果您对此有疑问,请添加评论 - 我还没有测试过它,但希望这足以让您开始。
您可以使用 内容类型,如果您愿意的话。
或者,您可以考虑查看处理喜好的现有可重用应用程序,例如 django-likes 或phileo。
You'll want to store ratings and books separately, something like this (untested).
unique_together
enforces that each user can only rate a given book once.You can then use this something like:
Add a comment if you have problems with this - I've not tested it, but hopefully this is enough to get you started.
You can probably avoid each object (books, publishers, comments, articles) having a separate rating object using content types, if you want.
Alternatively, you might consider looking at existing reusable apps that handle liking, like django-likes or phileo.
您可以在抽象模型中仅定义一次特殊方法(例如 vote、get_ rating 等),然后使用该方法创建“Rateable”模型。
此外,最好使用单一模型来存储内容类型的评级数据,正如多米尼克·罗杰 (Dominic Rodger) 所注意到的那样
You can define special methods (for example vote, get_rating, etc.) only onсe in abstract model and then create your "Rateable" models using this one.
Also it is better to use single model for storing rating data witch content types as noticed Dominic Rodger