[Django]-Using Django filters inside model function

5👍

An easy way to do this is by using classmethod decorator to make it a class method. Inside class Tasks:

@classmethod
def get_tasks_by_user(cls, userid):
    return cls.objects.filters(user_id=userid)

This way you can simply call:

tasks = Tasks.get_tasks_by_user(user_id)

Alternatively, you can use managers per Tom’s answer.

To decided on which one to choose in your specific case, you can refer James Bennett’s (the release manager of Django) blog post on when to use managers/classmethod.

👤K Z

4👍

Any methods on a model class will only be available to instances of that model, i.e. individual objects.

For your get_tasks_by_user function to be available as you want it (on the collection), it needs to be implemented on the model manager.

class TaskManager(models.Manager):
    def get_tasks_by_user(self, user_id):
        return super(TaskManager, self).get_query_set().filter(user=user_id)

class Task(models.Model):
    # ...
    objects = TaskManager()
👤Tom

Leave a comment