我想使用嵌套的序列化程序字段进行分组,并在其他字段上计算一些聚合函数。
我的模型类:
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')我希望将导入或导出作为查询参数发送,并对其应用聚合(avg) (由不同的国家/地区显示
我的视图类:
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'.发布于 2020-12-19 21:26:21
我已经找到了解决方案。实际上,序列化程序类中的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 datahttps://stackoverflow.com/questions/65369649
复制相似问题