Models.py:
class Car(models.Model):
Make_Name = models.CharField(max_length=100)
Model_Name = models.CharField(max_length=100)
def __str__(self):
return f'{self.Make_Name} {self.Model_Name}'
class Rating(models.Model):
RATING_CHOICES = (
(1,'1'),
(2,'2'),
(3,'3'),
(4,'4'),
(5,'5'),
)
rating = models.IntegerField(choices=RATING_CHOICES)
car = models.ForeignKey(Car,on_delete=models.CASCADE,related_name='rating')
Views.py
class CarViewSet(ListCreateAPIView):
serializer_class = CarSerializers
def get_queryset(self):
Car.objects.aggregate(average_rank = Avg('rating__rating'))
queryset = Car.objects.all()
return queryset
Serializers.py
class CarSerializers(serializers.ModelSerializer):
average_rank = serializers.DecimalField(decimal_places=3,max_digits=19,read_only=True)
class Meta:
model = Car
fields = ['Make_Name','Model_Name','average_rank']
ответ получаю в виде:
{
"Make_Name": "Honda",
"Model_Name": "Civic"
},
без поля
average_rank