47đ
Adding custom queries to managers is the Django convention. From the Django docs on custom managers:
Adding extra Manager methods is the preferred way to add âtable-levelâ functionality to your models.
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.
However, if youâre writing an app that youâre going to share with other Django users, then theyâll expect to see findBy
on a custom manager.
I donât think the inheritance issues you mention are too bad. If you read the custom managers and model inheritance docs, I donât think youâll get caught out. The verbosity of writing .objects
is bearable, just as it is when we do queries using XYZ.objects.get()
and XYZ.objects.all()
Hereâs a few advantages of using manager methods in my opinion:
-
Consistency of API. Your method
findBy
belongs withget
,filter
,aggregate
and the rest. Want to know what lookups you can do on theXYZ.objects
manager? Itâs simple when you can introspect withdir(XYZ.objects)
. -
Static methods âclutterâ the instance namespace.
XYZ.findBy()
is fine but if you define a static method, you can also doxyz.findBy()
. Running thefindBy
lookup on a particular instance doesnât really make sense. -
DRYness. Sometimes you can use the same manager on more than one model.
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 findBy
as a manager method, the sky isnât going to fall in đ
For further reading, I recommend the blog post Managers versus class methods by James Bennett, the Django release manager.