gpt4 book ai didi

python - 将原始 sql 映射到 django orm

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:31 24 4
gpt4 key购买 nike

有没有办法简化这个工作代码?此代码获取一个对象的所有不同投票类型,大约有 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)

最佳答案

下面的代码对我有用!

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

关于python - 将原始 sql 映射到 django orm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1150898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com