Login

Tag "count"

Snippet List

Aggregation class "Count" with Case

Use it like below: totals = MyClass.aggregate( is_enabled_yes=CountCase('is_enabled', when=True), is_enabled_no=CountCase('is_enabled', when=False), count_if=CountCase('id', case="another_field in ('a','b')", when=True), )

  • count
  • annotate
  • aggregation
Read More

Allow filtering and ordering by counts of related query results

I know you're thinking, *what the heck could that title mean?* I often find myself wanting to filter and order by the result of a COUNT(*) of a query using a method similar to the [entry_count example](http://www.djangoproject.com/documentation/db-api/#extra-select-none-where-none-params-none-tables-none). Writing this many times is tedious and hardcoding the table and column names made me cringe, I also wanted the counts to result from more complex queries. This is a method you can add to your custom Manager to do this easily. It's not an ideal syntax, but it's good for the amount of code required. Example: suppose we have some articles we want to filter and order by comments and visit logs to show the most popular... class ArticleManager(models.Manager): count_related = _count_related class Article(models.Model): pub_date = models.DateTimeField(auto_now_add=True) objects = ArticleManager() class Comment(models.Model): article = models.ForeignKey(Article) is_spam = models.BooleanField(default=False) class Visit(models.Model): article = models.ForeignKey(Article) referrer = models.URLField(verify_exists=False) search_query = models.CharField(maxlength=200) Notice how the ArticleManager is given the `count_related` method. Now you can find the most popular like so... Order by non-spam comments: Article.objects.count_related(Comment.objects.filter( is_spam=False)).order_by('-comment__count') Order by incoming non-search-engine links: Article.objects.count_related(Visit.objects.filter( referrer__isnull=False, search_query__isnull=True), 'links').order_by('-links') Order by total visits: Article.objects.count_related(Visit).order_by('-visit__count') Note: Doesn't work if `query` contains joins or for many-to-many relationships, but those could be made to work identically if there's demand.

  • sql
  • model
  • db
  • count
  • manager
Read More

3 snippets posted so far.