2

现在我正在学习 DRF,并且必须用相册做项目。我的任务之一是使用模型字段“标题”创建自定义@action“补丁”方法,但我不明白如何在自定义方法中添加搜索字段。我们可以在基本方法中看到它们,例如“get”、“patch”和“put”,但我找不到任何有关如何将它们添加到自定义操作的信息。如果有人知道该怎么做,请告诉我。

我的模型:

class PhotoAlbum(models.Model):
    title = models.CharField(verbose_name='Название альбома', max_length=50, null=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='Автор')
    created_at = models.DateTimeField(verbose_name='Дата создания', editable=False,
                                      default=datetime.datetime.today())

    class Meta:
        verbose_name = 'Фотоальбом'
        verbose_name_plural = 'Фотоальбомы'

    def __str__(self):
        return f'{self.title} Автор: {self.created_by} Дата: {self.created_at}'

我的观点:

def photo_album_view(request):
    photo_albums = PhotoAlbum.objects.all()
    context = {
        'photo_albums': photo_albums,
    }

    return render(request, 'photo_album.html', context=context)

我的观点:

class AlbumFilter(django_filters.FilterSet):
    title = django_filters.Filter(field_name='title')


class PhotoAlbumViewSet(viewsets.ModelViewSet):
    queryset = PhotoAlbum.objects.all()
    filterset_class = AlbumFilter
    serializer_class = PhotoAlbumSerializer
    pagination_class = ResultPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['title', ]
    ordering_fields = ['created_at', ]
4

1 回答 1

0

如果您正在使用ModelViewSet,我相信您正在寻找以下自定义方法之一:

def update(self, request, pk=None):
    pass

def partial_update(self, request, pk=None):
    pass

这些函数允许您向更新方法添加自定义功能。参考

简要示例:

def partial_update(self, request, pk=None):
            serializer = UserPostSerializer(user, data=request.data, partial=True)
            if serializer.is_valid():
                try:
                    serializer.save()
                except ValueError:
                    return Response({"detail": "Serializer not valid."}, status=400)
                return Response({"detail": "User updated."})
            else:
                return Response(serializer.errors)
于 2021-12-31T18:07:47.260 回答