Shift N' Tab Shift N' Tab - 25 days ago 7
Python Question

How to get Custom List in a Viewset

How can we write a function in a

ModelViewSet
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 = (
'this_id',
'name',
'species_type',
...,
)
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
@list_route()

but i can't understand it well.


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

Dap Dap
Answer

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

Serializer

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

alternatively, you can adopt a django filter framework http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend