Пользователь оценит историю.Лучше сослаться на StoryView (ModelViewSet) или создать другой.Или, может быть, есть еще один простой способ сделать это?
class Story(models.Model):
...
@property
def average_rating(self):
return self.rating_set.all().aggregate(Avg('rate'))['rate__avg']
class Rating(models.Model):
rate = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)])
story = models.ForeignKey(Story, on_delete=models.CASCADE)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
class Meta:
constraints = [
CheckConstraint(check=Q(rate__range=(0, 10)), name='valid_rate'),
UniqueConstraint(fields=['user', 'story'], name='rating_once')
]
urls.py
router.register('rate', StoryView, basename='rate')
views.py
class StoryView(viewsets.ModelViewSet):
queryset = Story.objects.all()
serializer_class = StorySerializer
...
serializers.py
class StorySerializer(serializers.ModelSerializer):
rate = serializers.FloatField(source='average_rating', read_only=True)
author = AuthorSerializer(read_only=True)
class Meta:
model = Story
fields = '__all__'