如何在视图中获取自定义列表
问题描述:
我们如何在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')
和视图集。
class AnimalViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = Animal.objects.all()
serializer_class = AnimalSerializer
我发现这个link有用的,例如像装饰
@list_route()
但我无法理解这一点很好。
我想从ViewSet中获取不同Animal.species_type
记录的列表。请帮忙。
答
过滤有几种不同的选项。您可以通过您的请求/animals?species_type=MusMusculus
发送物种类型,并在您使用视图中的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
这不是我的意思是,先生是什么,我想调用一个函数通过viewset获取数据库中所有不同的species_type记录。这意味着我不会对特定的species_type提出请求。 –
所以你只想要种类?我编辑了我的答案 – Dap
这意味着我们可以在另一个序列化类中定义它?听起来不错,我喜欢关于'url_path'的想法。 –