简体   繁体   English

在 Python 中,如何覆盖继承的 class 的 class 属性,该属性本身就是 model 的一个实例?

[英]In Python how can I overwrite the class attribute of an inherited class, where that attribute is itself an instance of a model?

As in the title, I have a base class ListView, with a Serializer attribute that needs overwriting.如标题所示,我有一个基本的 class ListView,它有一个需要覆盖的 Serializer 属性。 For each of my django models I create a child ListView class and a Serializer.对于我的每个 django 模型,我创建了一个子 ListView class 和一个序列化程序。 So for example for the django model Event we have a corresponding view class EventListView(ListView), and we have a corresponding Serializer class EventSerializer(Serializer).因此,例如对于 django model 事件,我们有一个对应的视图 class EventListView(ListView),并且我们有一个对应的序列化器 class EventSerializer(Serializer)。

The Serializer child class is specified within the ListViewClass, as in my code below. Serializer child class 在 ListViewClass 中指定,如下面的代码所示。 Is it possible to have the serializer overwritten automatically based on the value supplied to model, and how may I mark model and Serializer as attributes that are to be overwritten and therefore do not need values specified in the base class?是否可以根据提供给 model 的值自动覆盖序列化程序,我如何将 model 和序列化程序标记为要覆盖的属性,因此不需要在基 class 中指定的值?

class EventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = '__all__'

class ListView(APIView):
    model = <Model to be overwritten>        # Event is set as the default.
    Serializer = <Model Serializer to be overwritten>
    
    queryset = model.objects.all()

    def get(self,request):    
        # !!! Get filter conditions from request
        queryset = ListView.queryset.filter()    # !!! Filter conditions
        serializer = ListView.Serializer(queryset,many=True)
        return Response(serializer.data)

    def post(self,request):
        data = JSONParser.parse(request)
        serializer = ListView.Serializer(data = data)
        if serializer.is_valid():
            return Response(serializer.data, status = 201)
        else:
            return Response(serializer.errors, status = 400)


class EventListView(ListView):
    model = Event

I think you need to use self.queryset , self.model and self.Serializer instead of ListView.queryset and ListView.Serializer .我认为您需要使用self.querysetself.modelself.Serializer而不是ListView.querysetListView.Serializer Then, in each subclass it will use the queryset, model, and serializer of the subclass, rather than of the base ListView .然后,在每个子类中,它将使用子类的查询集 model 和序列化程序,而不是基类ListView的序列化程序。

In each subclass you will need to redefine model , queryset and Serializer .在每个子类中,您需要重新定义modelquerysetSerializer

class ListView(APIView):
    model = <Model to be overwritten>        # Event is set as the default.
    Serializer = <Model Serializer to be overwritten>
    
    queryset = model.objects.all()

    def get(self,request):    
        # !!! Get filter conditions from request
        queryset = self.queryset.filter()    # !!! Filter conditions
        serializer = self.Serializer(queryset,many=True)
        return Response(serializer.data)

    def post(self,request):
        data = JSONParser.parse(request)
        serializer = self.Serializer(data = data)
        if serializer.is_valid():
            return Response(serializer.data, status = 201)
        else:
            return Response(serializer.errors, status = 400)


class EventListView(ListView):
    model = Event
    Serializer = EventSerializer
    queryset = Event.objects.all()

If you don't want to define queryset on all subclasses, you probably want to add a method to get the queryset using the model, like this如果你不想在所有子类上定义查询集,你可能想添加一个方法来使用queryset获取查询集,就像这样

class ListView(APIView):
    model = <Model to be overwritten>        # Event is set as the default.
    Serializer = <Model Serializer to be overwritten>
    

    def get_queryset():
        return self.model.objects.all()

    def get(self,request):    
        # !!! Get filter conditions from request
        queryset = self.get_queryset().filter()    # !!! Filter conditions
        serializer = self.Serializer(queryset,many=True)
        return Response(serializer.data)

    def post(self,request):
        data = JSONParser.parse(request)
        serializer = self.Serializer(data = data)
        if serializer.is_valid():
            return Response(serializer.data, status = 201)
        else:
            return Response(serializer.errors, status = 400)

In fact, a lot of this is implemented directly in DRF, which will save you a lot of custom coding.事实上,其中很多都是直接在 DRF 中实现的,这将为您节省大量自定义编码。 Check out the GenericAPIView ( https://www.django-rest-framework.org/api-guide/generic-views/#genericapiview ) and ListAPIView ( https://www.django-rest-framework.org/api-guide/generic-views/#listapiview )查看GenericAPIView ( https://www.django-rest-framework.org/api-guide/generic-views/#genericapiview ) 和ListAPIView ( https://www.django-rest-framework.org/api-guide/generic-views/#listapiview )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 When using Generics types, how can I call an Attribute of an inherited class on the Base class instance with Python / Django? - When using Generics types, how can I call an Attribute of an inherited class on the Base class instance with Python / Django? 如何将_not_继承的属性添加到python * class *? - How to add attribute to python *class* that is _not_ inherited? 如何访问具有特定 Class 属性值的 Class 实例? - How can I access a Class instance with a certain Class attribute value? Python-用于对类属性进行操作的继承的类方法 - Python - inherited class method to operate on class attribute 删除继承类Python中的class属性 - Remove class attribute in inherited class Python 如何在Python中从继承的类设置和获取父类属性? - How to set and get a parent class attribute from an inherited class in Python? 如何在Python中添加类属性? - How I can add class attribute in Python? 为什么我无法在Python中访问instance .__ class__属性? - Why can't I access the instance.__class__ attribute in Python? 无法访问继承的Python类中的父级属性 - Can't access parent attribute in inherited Python class 当该属性本身是一个类本身时,如何将用户提供的参数分配给python属性 - How do I assign a user-supplied argument to a python attribute when that attribute is a class itself
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM