이 작업 코드를 단순화하는 방법이 있습니까? 이 코드는 모든 다른 투표 유형에 대해 객체를 가져옵니다. 가능한 20 가지가 있으며 각 유형이 포함됩니다. 원시 SQL을 작성하지 않고 orm을 사용하는 것을 선호합니다. 내가 모델에서 일반적인 외래 키를 사용하기 때문에 조금 더 까다 롭습니다.raw SQL을 django 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)
투표 객체는 생성 키를 사용하여 모든 객체에 투표 할 수 있기를 원합니다. 나는 모델 코드도 추가 할 것이다. – Stephan
당신은 외교 관계를 조사했다고 가정합니까? 그들은 당신이 원하는 특정 객체를 직접 만들 수있게 해줍니다. 예를 들어 답이있을 수 있습니다. http://www.djangoproject.com/documentation/models/generic_relations/ – AlbertoPL