【发布时间】:2010-11-12 03:53:08
【问题描述】:
有没有办法简化这个工作代码? 这段代码为一个对象获取所有不同的投票类型,大概有 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)
【问题讨论】:
标签: python sql django orm django-models