我如何在ModelSerializer上获取自定义字段

时间:2019-08-07 13:18:12

标签: django django-models django-serializer

我有一个模特

class Teacher(models.Model):
    name = models.CharField(max_length=100)
    message = models.CharField(max_length=300)
    status = models.OneToOneField(Dictionary, on_delete=models.CASCADE)
    money = models.IntegerField(default=None, blank=True, null=True)

我的网址

urlpatterns = [
    path('get', views.GetViewSet.as_view({'get': 'list'})),
]

我的观点

class GetViewSet(viewsets.ModelViewSet):

    def get_serializer_class(self):
        GeneralSerializer.Meta.model = Teacher
        return GeneralSerializer

    def post(self, request):
        return self.select_api()

    def select_api(self):
        queryset = Teacher.objects.values("name","money").annotate(Count("money"))
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

序列化器

class GeneralSerializer(serializers.ModelSerializer):
    class Meta:
        model = None
        depth = 2
        fields = '__all__'

在此示例中,我在带注释的功能中具有+1字段“ money__count”,但由于我的模型没有此字段,因此无法显示。我该如何在api中显示它并想要一个通用序列化器(不向序列化器中添加静态字段,因为它对于所有型号都是通用序列化器)

请帮助我

0 个答案:

没有答案