How to use a custom objects.filter() where some field filter out by default

Hello, I’ve share some code snippets for understanding the query that I have

class BaseModel(models.Model):
    created_at = models.DateTimeField(default=now)
    updated_at = models.DateTimeField(auto_now=True)
    is_deleted = models.BooleanField(default=False)

    class Meta:
        abstract = True
        
    def to_dict(self):
        data = model_to_dict(self)
        data["created_at"] = self.created_at
        data["updated_at"] = self.updated_at
        return data
    

class Interest(BaseModel):
    title = models.CharField(max_length=150)

    def __str__(self):
        return self.title

So here I’ve created a BaseModel which will be inherited by Interest model. So the thing I want is to create a custom query filter that I can use anywhere like to get all items which have is_deleted=False, I can use Interest.objects.filter(is_deleted=False). Instead of writing filter I need some predefined method like Interest.objects.filter_deleted() which will do the same Job and it should be applied to other models as well.

Maybe in class BaseModel their I can define some method or override some pre-defined method.

The feature you are looking for are either (or both) custom managers and custom querysets. See the docs at Managers | Django documentation | Django

1 Like

Well, can you try below code hope you can fix your error.

from django.db import models
from django.db.models import Manager

class BaseModelManager(Manager):
    def filter_deleted(self):
        return self.get_queryset().filter(is_deleted=False)

class BaseModel(models.Model):
    created_at = models.DateTimeField(default=now)
    updated_at = models.DateTimeField(auto_now=True)
    is_deleted = models.BooleanField(default=False)

    objects = BaseModelManager()

    class Meta:
        abstract = True

    def to_dict(self):
        data = model_to_dict(self)
        data["created_at"] = self.created_at
        data["updated_at"] = self.updated_at
        return data

class Interest(BaseModel):
    title = models.CharField(max_length=150)

    def __str__(self):
        return self.title

Blockquote

Thanks

Thanks @KenWhitesell and @Gulshan212, This is what I’ve been looking for :smiley:.