如何基于外键pk列出所有项目Django Rest Framework

xjreopfe  于 2023-05-19  发布在  Go
关注(0)|答案(2)|浏览(123)

我想列出保存到某个Animal的所有示例。假设一只狗的id为3,我有两个狗性别的示例,但是当我收到animal/3/sex的请求时,我只得到一个示例,而不是2。我尝试使用many=True来实现序列化器.PrimaryKeyRelatedField,但它显示“Animal不可迭代”。你知道怎么做吗?

class AnimalSex(models.Model):
    name = models.CharField(max_length=256)
    slug = models.SlugField(max_length=128, unique=True, null=False, editable=False)
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False)

观点

class MyAnimalSex(generics.RetrieveAPIView):

    queryset = AnimalSex.objects.all()
    serializer_class = AnimalSexSerializer
    lookup_field = 'pk'

串行器

class AnimalSexSerializer(serializers.ModelSerializer):

    animal = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = AnimalSex
        fields = ('name', 'slug', 'animal',)

网址

path('animal/<int:pk>/sex', MyAnimalSex.as_view()),
ssm49v7z

ssm49v7z1#

在这种情况下,您可能希望使用ListAPIView(docs)和基于Animal的主键的过滤器,因此:

class MyAnimalSex(generics.ListAPIView):
    queryset = AnimalSex.objects.all()
    serializer_class = AnimalSexSerializer

    def get_queryset(self):
        return super().get_queryset().filter(
            animal_id=self.kwargs['pk']
        )
thigvfpy

thigvfpy2#

可以使用lookup_field

class MyAnimalSex(generics.RetrieveAPIView):
    queryset = AnimalSex.objects.all()
    serializer_class = AnimalSexSerializer
    lookup_field = 'animal'

相关问题