我们如何在 ModelViewSet
中编写一个函数来获取数据库中不同记录的列表?
假设我们有这个模型。
class Animal(models.Model):
this_id = models.CharField(max_length=25)
name = models.CharField(max_length=25)
species_type = models.CharField(max_length=25)
...
和序列化器
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = (
'this_id',
'name',
'species_type',
...,
)
read_only_fields = ('id', 'created_at', 'updated_at')
和 View 集。
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.
我想从 ViewSet 中获取不同 Animal.species_type
记录的列表。请帮忙。
最佳答案
过滤中有多种不同的选项。您可以通过请求 /animals?species_type=MusMusculus
发送物种类型,并在覆盖 View 中的 get_queryset()
方法时引用它。
在你看来
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()
或者,您可以采用 django 过滤框架 http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend
关于python - 如何在 View 集中获取自定义列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40552874/