【问题标题】:How to override delete method (generics class) in django rest framework如何在 django rest 框架中覆盖删除方法(泛型类)
【发布时间】:2021-11-08 22:51:18
【问题描述】:

我正在尝试使用以下代码 sn-p 覆盖 generics.RetrieveUpdateDestroyAPIView 类中的删除方法。 :-

在views.py中

class ArtistView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = ArtistSerializer
    queryset = Users.objects.filter(user_type='artist')

在 serializers.py 中

class ArtistProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = ('profile_pic_url','cover_pic_url','full_name','genre','location')


class ArtistSerializer(serializers.ModelSerializer):

    profiles = ArtistProfileSerializer(many=False)

    class Meta:
        model = Users
        fields =  ['id','user_type', 'email', 'profiles','username']
        def delete(self, instance, *arg, **kwargs):
            profile = instance.profiles
            profile.delete()

在 urls.py 中

urlpatterns = [
path('all-artist/', views.ArtistListView.as_view()),
path('all-artist/<int:pk>', views.ArtistView.as_view())]

【问题讨论】:

    标签: python-3.x django-rest-framework django-views


    【解决方案1】:

    您不需要在 Serializer 中定义 delete() 方法(绝对不需要在 Meta 定义中)。

    应该为您处理删除逻辑,因为您在视图中派生自 RetrieveUpdateDestroyAPIView

    如果要添加自定义逻辑,则可以在视图中覆盖perform_destroy()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 2022-07-26
      • 2019-05-23
      • 2016-11-17
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      相关资源
      最近更新 更多