2009-07-19 3 views
1

이 작업 코드를 단순화하는 방법이 있습니까? 이 코드는 모든 다른 투표 유형에 대해 객체를 가져옵니다. 가능한 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) 

답변

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 
0

예, 확실히 ORM을 사용하여 사용하는 모델 임.

obj = Obj.objects.get(id=#the id) 
votes = obj.vote_set.all() 

에서 :이이 장고보기 기능 중 하나에있을 호출, 그리고

class Obj(models.Model): 
    #whatever the object has 

class Vote(models.Model): 
    obj = models.ForeignKey(Obj) #this ties a vote to its object 

객체에서 투표를 모두 얻을 : 당신이 정말 일을해야하는 것은이 모델에 그것들을 계산하는 방법을보기가 상당히 쉽습니다 (투표라는리스트의 길이를 얻으십시오).

문서에서 다 대일 관계에 대해 읽는 것이 좋습니다. 매우 편리합니다.

http://www.djangoproject.com/documentation/models/many_to_one/

+0

투표 객체는 생성 키를 사용하여 모든 객체에 투표 할 수 있기를 원합니다. 나는 모델 코드도 추가 할 것이다. – Stephan

+0

당신은 외교 관계를 조사했다고 가정합니까? 그들은 당신이 원하는 특정 객체를 직접 만들 수있게 해줍니다. 예를 들어 답이있을 수 있습니다. http://www.djangoproject.com/documentation/models/generic_relations/ – AlbertoPL

관련 문제