Shift N' Tab Shift N' Tab - 9 months ago 42
Python Question

How to get Custom List in a Viewset

How can we write a function in a

that get a list of distinct record in the database?

Supposed that we have this model.

class Animal(models.Model):

this_id = models.CharField(max_length=25)
name = models.CharField(max_length=25)
species_type = models.CharField(max_length=25)

and serializer

class AnimalSerializer(serializers.ModelSerializer):

class Meta:
model = Animal
fields = (
read_only_fields = ('id', 'created_at', 'updated_at')

and ViewSet.

class AnimalViewSet(viewsets.ModelViewSet):
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
queryset = Animal.objects.all()
serializer_class = AnimalSerializer

I found this link useful such as decorators like

but i can't understand it well.

I would like to get list of distinct
record from the ViewSet. Please help.

Dap Dap
Answer Source

There are several different options in filtering. You can send the species type via your request /animals?species_type=MusMusculus and reference it when you over ride the get_queryset() method in the view.

In your view

def get_queryset(self):
    species = self.request.query_params.get('species_type', None)
    if species is not None:
        queryset = Animals.objects.all().distinct('species_type')
        species = SpeciesSerializer(data=queryset)
    return queryset


from rest_framework import serializers
class Species(serializers.Serializer):
    species_type = serializers.Charfield()

alternatively, you can adopt a django filter framework