【问题标题】:Group by and Aggregate with nested Field分组并与嵌套字段聚合
【发布时间】:2020-12-19 12:06:45
【问题描述】:

我想用嵌套的序列化器字段分组,并在其他字段上计算一些聚合函数。

我的模型课程:

class Country(models.Model):
    code = models.CharField(max_length=5, unique=True)
    name = models.CharField(max_length=50)

class Trade(models.Model):
    country = models.ForeignKey(
        Country, null=True, blank=True, on_delete=models.SET_NULL)
    date = models.DateField(auto_now=False, auto_now_add=False)
    exports = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    imports = models.DecimalField(max_digits=15, decimal_places=2, default=0)

我的序列化程序类:

class CountrySerializers(serializers.ModelSerializer):
    class Meta:
        model = Country
        fields = '__all__'


class TradeAggregateSerializers(serializers.ModelSerializer):
    country = CountrySerializers(read_only=True)
    value = serializers.DecimalField(max_digits=10, decimal_places=2)

    class Meta:
        model = Trade
        fields = ('country','value')

我想将导入或导出作为查询参数发送并对其应用不同国家/地区显示的聚合(平均值)

我的视图类:

class TradeAggragateViewSet(viewsets.ModelViewSet):
    queryset = Trade.objects.all()
    serializer_class = TradeAggregateSerializers

    def get_queryset(self):
        import_or_export = self.request.GET.get('data_type')
        queryset = self.queryset.values('country').annotate(value = models.Avg(import_or_export))
    return queryset

我想以如下格式获取数据:

[
    {
        country:{
            id: ...,
            code: ...,
            name: ...,
        },
        value:...
    },
    ...
]

但国家序列化程序出错

AttributeError: Got AttributeError when attempting to get a value for field `code` on serializer `CountrySerializers`. 
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. 
Original exception text was: 'int' object has no attribute 'code'.

【问题讨论】:

  • Django 查询集没有value 属性。将其更改为:queryset = self.queryset.values('country').annotate(value = models.Avg(import_or_export))

标签: python django django-rest-framework


【解决方案1】:

我找到了解决方案。实际上,序列化程序类中的 to_representation 只得到国家的 id 而不是它的对象,所以我将 to_representation 覆盖为:

class TradeAggregateSerializers(serializers.ModelSerializer):
...
...
    def to_representation(self, instance):
        #instance['country'] = some id, not object
        #getting actual object
        country =  Country.objects.get(id=instance['country'])
        instance['country'] = country
        data = super(TradeAggregateSerializers, self).to_representation(instance)
        return data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 2021-03-19
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多