Skip to content

Instantly share code, notes, and snippets.

@n1k0
Created April 22, 2010 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n1k0/375770 to your computer and use it in GitHub Desktop.
Save n1k0/375770 to your computer and use it in GitHub Desktop.
from django.db import models
from django.db.models import Avg, Max, Min, Count
class Fortune(models.Model):
author = models.CharField(max_length=45, blank=False)
title = models.CharField(max_length=200, blank=False)
content = models.TextField(blank=False)
pub_date = models.DateTimeField('date published', auto_now_add=True)
votes = models.IntegerField(default=0)
def __unicode__(self):
return "%s, from %s" % (self.title, self.author)
@staticmethod
def top_authors(max):
return Fortune.objects.values('author').annotate(nb=Count('id')).order_by('-nb')[:max]
-- Retrieves top fortune authors
SELECT author, count(id) AS nb FROM fortunes GROUP BY author ORDER BY nb DESC;
@olivierverdier
Copy link

  1. you should never use @staticmethod in python; use @classmethod instead
  2. for Django, what you are doing is typically achieved by a custom Manager class, rather than with a class method

(you have used symfony for too long ;-)

@n1k0
Copy link
Author

n1k0 commented Apr 23, 2010

Ah, nice to know! I'll check out managers asap. Thanks for the kind feedback :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment