Django 1.6是否有更好的多模型投票模型设计?
查询愿望: 1.根据4个模型的属性Django 1.6是否有更好的多模型投票模型设计?,django,Django,查询愿望: 1.根据4个模型的属性score对其进行排序(将来可能会更多)。据说这是非常缓慢的: #`Item` represent Question, Answer, Topic or Reply. sorted(Item.objects.all(),key=lambda i:i.score) 2.列出用户或项目的投票历史记录。显然,这是通过模型投票自然解决的。但是如果设计中没有这样的模型,那么这个愿望应该通过其他方式实现 我当前的解决方案是在四个模型中添加一个整数字段rate,这样每当投票
score
对其进行排序(将来可能会更多)。据说这是非常缓慢的:
#`Item` represent Question, Answer, Topic or Reply.
sorted(Item.objects.all(),key=lambda i:i.score)
2.列出用户或项目的投票历史记录。显然,这是通过模型投票
自然解决的。但是如果设计中没有这样的模型,那么这个愿望应该通过其他方式实现
我当前的解决方案是在四个模型中添加一个整数字段rate
,这样每当投票操作发生在它身上时,除了在modelvote
中添加一条记录外,它的rate
字段可以用属性score
中的值保存。但是有更好的设计吗?谢谢
这是相关的模型:
#models.py
class BaseAction(models.Model):
class Meta:
abstract = True
user = models.ForeignKey(User)
create_time = models.DateTimeField(auto_now_add=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey("content_type", "object_id")
class Vote(BaseAction):
value = models.IntegerField(default=0) #all possible value is -1,0 and 1
class BaseItem(models.Model):
class Meta:
abstract = True
user = models.ForeignKey(User)
content = models.TextField()
vote = generic.GenericRelation(Vote)
@property
def score(self):
'''
this is the key method to sort a model.
'''
return sum([a.value for a in self.vote.all()])
#---there are 4 models that can be voted, maybe more in the future.------
class Question(BaseItem):
title = models.CharField(max_length=50)
class Answer(BaseItem):
question = models.ForeignKey(Question)
class Topic(BaseItem):
title = models.CharField(max_length=50)
class Reply(BaseItem):
topic = models.ForeignKey(Topic)
您不需要两个抽象的基本模型,我真的认为您需要重新考虑您的数据库设计。@Burhan Khalid在我的项目中还有4个其他模型子类
BaseAction
。我认为这是干的,就像BaseItem
一样。你能解释一下原因吗?