I want to group by with nested serializer field and compute some aggregate function on other fields.
My Models Classes:
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)
My Serializer Classes:
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')
I want to send import or export as query parameters and apply aggregate (avg) over it shown by distinct countries
My View Class:
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
I want to get the data in format like:
[
{
country:{
id: ...,
code: ...,
name: ...,
},
value:...
},
...
]
But having an error on country serializer
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'.
I have found the solution. Actually to_representation in serializer class got only the id of country not its object so i override to_representation as:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.