How to filter queryset from inside the serializer?
I want to always apply a filter to a serializer (filter the queryset). lets say I have:
class Company(models.Model):
name = models.CharField(max_length=90, unique=True)
city = models.CharField(max_length=90,)
active = models.BooleanField(default=True)
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model=Company
fields=['id', 'name', 'city']
so when I call the serializer for a list filtered by city (or any other fields added in my real code) as shown below it returns Companies from that city and only "active=True"
query_set = Company.objects.filter(city=request.POST(city) )
srl = serializers.CompanySerializer(query_set, many=True)
return Response(srl.data)
because I may want to call the serializer from other parts of the code. and I want to keep the records for reference but never show to any client. I have tryed to modify the queryset from from init but it does not work. I actually print() the modified queryset to make sure it was filtered and it prints the filtered queryset, I do:
def __init__(self, instance=None, data=empty, **kwargs):
instance.filter(active=False)
self.instance = instance
print(self.instace) #this prints the filtered queryset OK
but it sends the response without the "active=False" filter.