33

I am creating a simple application with Django. I realized that I am doing the same kind of operations very often. For example I often need to get all Article objects which have isPublick = True. So I am wondering, is it possible to define a get_published function in the model?

If the model looks like this (simplified)

class Article(models.Model):
    title = models.CharField(...)
    isPublished = models.BooleandField()

    def get_active(self):
       return Article.objects.filter(isPublicshed = 1)

But this doesn't seem to work.

Can you suggest a way of implementing the function?

3 Answers 3

87

What you probably want is a custom manager

From the django docs:

        # An example of a custom manager called "objects".

class PersonManager(models.Manager):
    def get_fun_people(self):
        return self.filter(fun=True)

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    fun = models.BooleanField()
    objects = PersonManager()

    def __unicode__(self):
        return u"%s %s" % (self.first_name, self.last_name)

which then allows you to do something like:

>>> p1 = Person(first_name='Bugs', last_name='Bunny', fun=True)
>>> p1.save()
>>> p2 = Person(first_name='Droopy', last_name='Dog', fun=False)
>>> p2.save()
>>> Person.objects.get_fun_people()
[<Person: Bugs Bunny>]
Sign up to request clarification or add additional context in comments.

2 Comments

Good code example. Succinctly explained a part of django that previously seemed pointless to me (in my noobosity). +1.
It is also worth mentioning, that in order for this to work and avoid NameErrors, you need to write the manager class above the object class, for it to recognize it.
24

As is stated in the docs here, if you need to add custom row-level functionality to your objects, you need to define custom methods on your models. However, if what you are after is custom table-wide functionality (such as getting all Article objects that qualify certain conditions), you have to define custom methods on model Managers (much as aciniglio above points out in their answer).

Comments

20

You can use the staticmethod decorator.

class Article(models.Model):
    title = models.CharField(...)
    isPublished = models.BooleandField()

    @staticmethod
    def get_active():
        return Article.objects.filter(isPublished = 1)

2 Comments

Thanks for bringing this up! Answered my, different, question.
This should be a classmethod instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.