有没有办法简化这个工作代码? 这段代码为一个对象获取所有不同的投票类型,有20种可能,并计算每种类型。 我不想写原始的SQL但使用orm。这有点棘手,因为我在模型中使用通用外键。
def get_object_votes(self, obj):
"""
Get a dictionary mapping vote to votecount
"""
ctype = ContentType.objects.get_for_model(obj)
cursor = connection.cursor()
cursor.execute("""
SELECT v.vote , COUNT(*)
FROM votes v
WHERE %d = v.object_id AND %d = v.content_type_id
GROUP BY 1
ORDER BY 1 """ % ( obj.id, ctype.id )
)
votes = {}
for row in cursor.fetchall():
votes[row[0]] = row[1]
return votes
使用
的模型class Vote(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
payload = generic.GenericForeignKey('content_type', 'object_id')
vote = models.IntegerField(choices = possible_votes.items() )
class Issue(models.Model):
title = models.CharField( blank=True, max_length=200)
答案 0 :(得分:1)
以下代码为我做了诀窍!
def get_object_votes(self, obj, all=False):
"""
Get a dictionary mapping vote to votecount
"""
object_id = obj._get_pk_val()
ctype = ContentType.objects.get_for_model(obj)
queryset = self.filter(content_type=ctype, object_id=object_id)
if not all:
queryset = queryset.filter(is_archived=False) # only pick active votes
queryset = queryset.values('vote')
queryset = queryset.annotate(vcount=Count("vote")).order_by()
votes = {}
for count in queryset:
votes[count['vote']] = count['vcount']
return votes
答案 1 :(得分:0)
是的,绝对使用ORM。你应该在你的模型中做到这一点:
class Obj(models.Model):
#whatever the object has
class Vote(models.Model):
obj = models.ForeignKey(Obj) #this ties a vote to its object
然后要从对象获得所有投票,请将这些Django调用放在您的一个视图函数中:
obj = Obj.objects.get(id=#the id)
votes = obj.vote_set.all()
从那里可以很容易地看出如何计算它们(得到名单的长度称为投票)。
我建议从文档中阅读多对一关系,这非常方便。
http://www.djangoproject.com/documentation/models/many_to_one/