将额外的信息传递给Django rest框架中的序列化器字段

时间:2018-08-12 18:58:19

标签: django django-rest-framework django-serializer

我正在尝试计算每个用户给出的餐厅的平均评分。我有餐厅的单独模型和用户给每个餐厅的评级。在我的ReviewSerializer中,我想为平均收视率添加额外的字段。我确实计算了平均评分。根据{{​​3}},我可以使用 get_serializer_context 方法将额外的数据传递给序列化器。我尝试传递硬编码的字符串,它可以正常工作,但是我不知道如何将get_avg_rating方法返回的响应传递给上下文

Views.py

class ReviewsView(generics.ListCreateAPIView):
   queryset = Reviews.objects.all()
   serializer_class = ReviewSerializer

   def perform_create(self,serializer):
      serializer.save()

   def get_avg_rating(request):

      avg = []
      for place in Places.objects.all():
         avg_rating = Reviews.objects.filter(place__id=place.id).aggregate(Avg('rating'))
         avg_value = round(avg_rating['rating__avg'],2)       
         avg.extend([place , avg_value])           
      return HttpResponse(avg,content_type="json")

    def get_serializer_context(self):

       context = super(ReviewsView, self).get_serializer_context()
       context.update({
        "test": {'test':'test'}

    })

    return context

Serializers.py

class ReviewSerializer(serializers.ModelSerializer):

user = serializers.ReadOnlyField(source='user.user.username')   
test_object = serializers.SerializerMethodField()

def get_test_object(self,obj):        
    test_value = self.context.get('test')  
    return avg_value

class Meta:

    model = Reviews
    fields = ('id','user','review','test_object')

Models.py

class Reviews(models.Model):
restaurant = models.ForeignKey(Places,on_delete=models.CASCADE,related_name='reviews')
user = models.ForeignKey(CustomUsers,on_delete=models.CASCADE)
RATING_CHOICE = (
    (1, 1),
    (1.5, 1.5),
    (2, 2),
    (2.5, 2.5),
    (3, 3),
    (3.5, 3.5),
    (4, 4),
    (4.5, 4.5),
    (5, 5),
)

rating = models.DecimalField(default=0.0, choices=RATING_CHOICE, decimal_places=1, max_digits=3)
review = models.CharField(max_length=500,default='',null=True)

def __str__(self):
    return self.place.name

class Meta:
    verbose_name_plural = "Reviews"

0 个答案:

没有答案