Задать вопрос

Тел: +7 965 3737 888





Allow filtering and ordering by counts of related query results

<p>I know you're thinking, <em>what the heck could that title mean?</em></p>
<p>I often find myself wanting to filter and order by the result of a COUNT(*) of a query using a method similar to the <a href="http://www.djangoproject.com/documentation/db-api/#extra-select-none-where-none-params-none-tables-none">entry_count example</a>. 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.</p>
<p>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.</p>
<p>Example: suppose we have some articles we want to filter and order by comments and visit logs to show the most popular...</p>
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)

<p>Notice how the ArticleManager is given the count_related method. Now you can find the most popular like so...</p>
<p>Order by non-spam comments:</p>

<p>Order by incoming non-search-engine links:</p>
    referrer__isnull=False, search_query__isnull=True),

<p>Order by total visits:</p>

<p>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.</p>

Вопрос полезен? Да0/Нет0

Ответы (2):

Ответ полезен? Да0/Нет0

I'm definitely interested in getting this to work with many-to-many relationships. What would be involved in doing so?

Ответ полезен? Да0/Нет0

Hmm, it seems that filter doesn't actually see the attribute added by count_related. It must be possible since order_by sees it just fine... probably a shortcoming of QuerySet.