Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>While adam's solution is correct, a more django-ish way would be to use a manager.</p> <p>See <a href="http://www.b-list.org/weblog/2008/feb/25/managers/" rel="nofollow noreferrer">Managers versus class methods</a> on James Bennett's blog</p> <p>Among other advantages :</p> <ul> <li>a manager carries all query-specific code, while avoiding to clutter the model class</li> <li>the same manager class can be shared among several classes</li> <li>the manager can be used directly on a model class, or via a one-to-many or m2m relation</li> </ul> <p>Thus, for the above question :</p> <pre><code>from django.db import models from django.db.models.manager import Manager class ProductScoreManager(Manager): use_for_related_field = True def top_score(self, limit=2): return self.get_query_set().order_by('-score')[:limit] </code></pre> <p>Then add this manager class as <em>default manager</em> for Product :</p> <pre><code>class Product(models.Model): ... objects = ProductScoreManager() ... </code></pre> <p>Now, thanks to <em>objects</em> overriding the default manager, and <em>use_for_related_field</em> allowing its use in relation queries, the top_score method can be used in any model related to products.</p> <pre><code>myproducttype = ProductType.objects.get(...) myproducttype.products.top_score() # return top 2 products </code></pre> <p>This allows a more consistent syntax : the related products is always accessed via <em>products</em>, <em>top_score</em> acting as a filter. Additionally, ProductType class is no more cluttered with Product's query logic.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload