python - 如何在 View 集中获取自定义列表

标签 python django django-models django-rest-framework

我们如何在 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/

相关文章:

python - Django 自引用关系?

python根据日期元素从1个列表中排序列表

python - 通过继承 MaintenanceRequest 模型,通知维护团队成员有关新请求的信息

python - 需要检查测验中的答案是否正确(Python)

python - Django--Windows 上的 django-admin.py 不起作用

django - 如何为设计师的开发环境设置 Django/Apache

django - 如何加入具有同一用户外键的多个模型的结果?

python - PyCrypto 和 GMP 库未找到错误 [Mac OS 10.6.3]

python - 如何在管理中的django modelform中访问request.user

python - Django 管理员 : Accesing the parent instance within an Inline admin