[Django]-Filter by is_active boolean field in django

4👍

You can write custom model manager:

class IsActiveManager(models.Manager):
    def get_queryset(self):
        return super(IsActiveManager, self).get_queryset().filter(is_active=True)

class Crew(models.Model):
    ...
    objects = IsActiveManager()

Now Crew.objects.all() will return only is_active record.

2👍

You can write a mixin in mixin.py file something like this

class TimeFieldsMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True, db_index=True)
    class Meta:
        abstract = True

And Import this in your models like this:

class User(TimeFieldsMixin):
     // model fields

This will add this fields by default wherever you use this mixin.

Let me know if this is not clear.

0👍

Please note that if you have additional Model Managers:

The first manager listed in the model class definition is the one that is used for the admin site and a number of other operations.

Leave a comment