2
Django Model
definitions define the tables to store records and they also define what an instance of that object looks like and how it behaves. objects
is a special attribute on a Model
class (not on the instances) that allow you to do things to all of the instances (such as query the tables). objects
is a type of ModelManager
.
What you want to do is define a custom manager.
Let’s say you have a model definition like so:
class SomeModel(models.Model):
pass
Well, you can define a custom manager for your model with a custom method like so:
class SomeModelManager(models.Manager):
def datesort(self):
return self.order_by('-date')
Now, you can attach your manager to your model definition and give it whatever name you want:
class SomeModel(models.Model):
sorting = SomeModelManager()
Now, you can import and use that sorting Manager:
>>> from some_app.models import SomeModel
>>> SomeModel.sorting.date() # Not called on an instance!
[sorted results]
The key thing to realize is that you do not want to work on instances of SomeModel
, but the actual ModelManager itself. This is often confusing in Django because you get to them by interacting with the same class.
See the docs for more info: