如何在Django Rest Framework中清理@property变量的json输出

时间:2019-11-21 05:25:34

标签: python django django-rest-framework

问题是,当我对此模型进行get请求时,JSON响应并不干净,难以在Retrofit中使用。

这是JSON输出示例:

[
    {
        "id": 1,
        "restName": "Buddy's",
        "banner": "http://127.0.0.1:8000/media/buddysImg.jpg",
        "zipcode": 48212,
        "restRating": {
            "rating__avg": 4.0
        },
        "website": "Buddys.com",
        "phone": 3138929001,
        "restPrice": 0.0
    }
]

这就是我想要的样子:

[
    {
        "id": 1,
        "restName": "Buddy's",
        "banner": "http://127.0.0.1:8000/media/buddysImg.jpg",
        "zipcode": 48212,
        "restRating": 4.0,
        "website": "Buddys.com",
        "phone": 3138929001,
        "restPrice": 0.0
    }
]

这是我的模特:

class Rest(models.Model):
    restName = models.CharField(max_length=50, null=False, default = " ")
    zipcode = models.PositiveIntegerField( null=False, default = 0)
    #restRating = models.FloatField( null=False, default = 0)
    banner = models.ImageField( null=True) 
    website = models.CharField(max_length=50, null=False, default = " ")
    phone = models.PositiveIntegerField( null=False, default = 0)
    restPrice = models.FloatField( null=False, default = 0)

    @property
    def restRating(self):
        avg = Rating.objects.filter(restId=self.pk).aggregate(Avg('rating'))
        return avg

    def __str__(self):
        return self.restName

这是我的序列化器:

class restSerializer(serializers.ModelSerializer):
    restRating = serializers.FloatField

    class Meta:
        model = Rest
        fields = ['id', 'restName', 'banner', 'zipcode', 'restRating', 'website', 'phone', 'restPrice']       

谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您只能返回属性中的值。您需要将属性更改为此:

@property
def restRating(self):
    avg = Rating.objects.filter(restId=self.pk).aggregate(Avg('rating'))['rating__avg']
    return avg

来自aggregate文档:

  

aggregate()是QuerySet的终端子句,调用该子句时,   返回名称-值对的字典。名称是一个标识符   总价值;该值是计算得出的总和。名字   是根据字段名称自动生成的,   聚合函数。