Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Adding custom queries to managers is the Django convention. From the Django docs on <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers" rel="noreferrer">custom managers</a>:</p> <blockquote> <p>Adding extra Manager methods is the preferred way to add "table-level" functionality to your models.</p> </blockquote> <p>If it's your own private app, the convention word doesn't matter so much - indeed my company's internal codebase has a few classmethods that perhaps belong in a custom manager. </p> <p>However, if you're writing an app that you're going to share with other Django users, then they'll expect to see <code>findBy</code> on a custom manager.</p> <p>I don't think the inheritance issues you mention are too bad. If you read the <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance" rel="noreferrer">custom managers and model inheritance docs</a>, I don't think you'll get caught out. The verbosity of writing <code>.objects</code> is bearable, just as it is when we do queries using <code>XYZ.objects.get()</code> and <code>XYZ.objects.all()</code></p> <p>Here's a few advantages of using manager methods in my opinion:</p> <ol> <li><p>Consistency of API. Your method <code>findBy</code> belongs with <code>get</code>, <code>filter</code>, <code>aggregate</code> and the rest. Want to know what lookups you can do on the <code>XYZ.objects</code> manager? It's simple when you can introspect with <code>dir(XYZ.objects)</code>. </p></li> <li><p>Static methods "clutter" the instance namespace. <code>XYZ.findBy()</code> is fine but if you define a static method, you can also do <code>xyz.findBy()</code>. Running the <code>findBy</code> lookup on a particular instance doesn't really make sense.</p></li> <li><p>DRYness. Sometimes you can use the same manager on more than one model.</p></li> </ol> <p>Having said all that, it's up to you. I'm not aware of a killer reason why you should not use a static method. You're an adult, it's your code, and if you don't want to write <code>findBy</code> as a manager method, the sky isn't going to fall in ;)</p> <p>For further reading, I recommend the blog post <a href="http://www.b-list.org/weblog/2008/feb/25/managers/" rel="noreferrer">Managers versus class methods</a> by James Bennett, the Django release manager.</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