Django Rest框架 - 获取总行数

时间:2018-04-29 21:47:32

标签: django count django-rest-framework

我想输出一个计算Candidat模型中Candidat数量的字段。我目前正在使用以下序列化程序:

class CountCSerializer(serializers.ModelSerializer):
    user_count = serializers.SerializerMethodField()

    class Meta:
        model = Candidat
        fields = ( 'user_count',)   

    def get_user_count(self, obj):
        return Candidat.objects.count()

以及以下api:

class CountCViewSet(ModelViewSet):
    queryset = Candidat.objects.all()
    serializer_class = CountCSerializer

urls.py:

router.register(r'CountC', CountCViewSet, base_name='users-count')

models.py:

class Candidat(models.Model):           
    name = models.CharField(max_length=50)
    lastName = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    tel = models.CharField(max_length=50, default=0)
    password = models.CharField(max_length=50)
    civility = models.CharField(max_length=50)
    birthDate = models.DateField(auto_now=False, auto_now_add=False)
    gouvernorate = models.CharField(max_length=50)
    def __str__(self):
        return "Candidat: {}".format(self.name)

但我一无所获!

enter image description here

非常感谢任何有关此事的帮助。

0 个答案:

没有答案