views:

495

answers:

2

Is there a way to simplify this working code? This code gets for an object all the different vote types, there are like 20 possible, and counts each type. I prefer not to write raw sql but use the orm. It is a little bit more tricky because I use generic foreign key in the model.

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

The models im using

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)
A: 

Yes, definitely use the ORM. What you should really be doing is this in your model:

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

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

Then to get all of the votes from an object, have these Django calls be in one of your view functions:

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

From there it's fairly easy to see how to count them (get the length of the list called votes).

I recommend reading about many-to-one relationships from the documentation, it's quite handy.

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

AlbertoPL
The vote object uses a generig foreing key , I want to be able to vote on any object. i will add the model code too.
Stephan
I assume you have investigated foreign relations? They let you directly create the particular object you want. The example looks like may have the answer. http://www.djangoproject.com/documentation/models/generic_relations/
AlbertoPL
+1  A: 

The code Below did the trick for me!

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
Stephan