Sahana Prabhakar
Sahana Prabhakar

Reputation: 581

filter by is_active boolean field in django

I want to have an is_active field for all the models in my application and when ever I create an api, I want to filter only the active ones and send the response. Is there a generic way to do this? As of now I am keeping a boolean field is_active and every time I retrieve the objects, I am writing a filter. below is the code :

My models.py

class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
    is_active = models.BooleanField(default=True)

My views.py :

@api_view(['GET'])
def get_crews(request):
    c = Crew.objects.filter(is_active=True)
    serializer = CrewSerializer(c, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

Upvotes: 3

Views: 6236

Answers (3)

chris Frisina
chris Frisina

Reputation: 19688

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.

Upvotes: 0

neverwalkaloner
neverwalkaloner

Reputation: 47374

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.

Upvotes: 4

Kishan Mehta
Kishan Mehta

Reputation: 2678

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.

Upvotes: 2

Related Questions