Andrey Krasnikov
Andrey Krasnikov

Reputation: 11

Function for every a django-model

I have django-models and I made a function, for example:

def function(django-model):
    return django-model.objects.order_by('-date')

I want execute function for all models, but I don't know how it works.

function(django-model-1())

or

function(django-model-2)

return:

AttributeError: Manager isn't accessible via django-model-1 instances

Thanks for help and sorry for my English.

Upd:

Sorry, maybe I poorly explained.

I need a universal function for manipulating models.

from django-model-1.models import django-model-1
from django-model-2.models import django-model-2

    def function(django-model):
        return django-model.objects.order_by('-date') # This is only for example

function(django-model-1)
function(django-model-2)

But it's don't work.

If I make without the function, it's work.

django-model-1.objects.order_by('-date')

Upvotes: 1

Views: 322

Answers (1)

erewok
erewok

Reputation: 7835

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:

https://docs.djangoproject.com/en/1.9/topics/db/managers/

Upvotes: 2

Related Questions