我正在和django和DRF一起做一个项目。我遇到了这个错误AssertionError at /barber/info/ The field 'comments' was declared on serializer BarberSerializer, but has not been included in the 'fields' option.
我不知道为什么我面临这个错误,尽管我已经添加了'评论'在我的领域。这是我的serializer:
class BarberSerializer(serializers.ModelSerializer):
comments = CommentSerializer(many=True)
rating = serializers.SerializerMethodField(source= "get_rating")
customers_rate = serializers.SerializerMethodField()
# comments = serializers.SerializerMethodField()
# rating = serializers.SerializerMethodField()
# comment_body = serializers.CharField(write_only=True, required=False)
class Meta:
model = Barber
fields = ('id','BarberShop','Owner','phone_Number','area','address','rate', "rating",
"customers_rate", 'background','logo', 'comments', )# ,"comment_body", ]# "rating"]
read_only_fields = ("id", "created_at", "BarberShop", "Owner", "phone_Number", "area", "address" ,
'background','logo',"comments", "rate", "rating", "customers_rate")
def get_comments(self, obj):
comments = obj.comments.all()
serializer = CommentSerializer(comments, many=True, context=self.context)
return serializer.data
def get_rating(self, obj):
comments = obj.comments.all()
if comments:
ratings = [comment.rating for comment in comments]
return sum(ratings) / len(ratings)
return 0
def get_rating(self,obj):
ratings = obj.ratings.all()
if ratings :
ratings = [rating_instance.rating for rating_instance in ratings]
# print(*ratings, sep = "\*n")
return round(sum(ratings) / len(ratings), 2)
else:
return 3.33
def get_customers_rate(self, obj):
customer = self.context['request'].user.customer
# print(customer, sep = "*****\n")
try:
rating = obj.ratings.filter(customer=customer).order_by("-created_at").first()
# rating = Rating.objects.get(customer= customer, barber = obj)
return rating.rating
except:
return 3.33
# def create(self, validated_data):
# validated_data['customer'] = self.context['request'].user.customer
# return super().create(validated_data)
# services = ServiceSerializer(many=True)
categories = CategorySerializer(many=True)
class Meta:
model = Barber
fields = ['id','BarberShop','Owner','phone_Number','area','address','rate','background','logo','categories']
我不知道是什么问题。
1条答案
按热度按时间guicsvcw1#
我正在检查我的代码,刚刚意识到我在类的两个部分使用了 meta类,这导致了这个错误。