python - 从另一个模型向序列化器添加额外的字段

标签 python django python-3.x django-models django-rest-framework

我将在我的项目中将模型包含到另一个序列化器中,这里是规范。我有一个评论模型如下

class Review(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    rating= models.ForeignKey(ProductRating, on_delete=models.DO_NOTHING)
    comment = models.TextField()

我的功能是显示用户为产品写的评论数量,我应该像那样在序列化程序中显示

class WishList(models.Model):
    user = models.ForeignKey('authentication.User', on_delete=models.CASCADE, null=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)

serailzier.py

class GetWishlistSerializer(serializers.ModelSerializer):

name = serializers.CharField(source='product.name', read_only=True)
rating = serializers.IntegerField(source='product.rating', read_only=True)
image = serializers.ImageField(source='product.image', read_only=True)
price = serializers.DecimalField(source='product.price', decimal_places=2, max_digits=10, read_only=True)
review = SerializerMethodField()

class Meta:
    model = WishList
    fields = ['user','product', 'name', 'rating', 'image', 'price', 'description', 'review']

def get_review(self, obj):
    return Review.objects.filter(product_id=obj.id).count()

它应该计算指定产品的评论数量,但它没有工作,它给出了这样的结果。

{
            "user": 1,
            "product": 1,
            "name": "Samsung A70",
            "rating": 5,
            "image": "http://localhost:8000/media/products/2019/08/30/wkl6pb_E2RUzH6.jpeg",
            "price": "2500.00",
            "description": "bla bla bla",
            "review": 0
        }

但我有一个关于产品的评论:1 它应该显示 1 但它显示 0 我不知道我在这里遗漏了什么。有什么帮助吗?如果问题不清楚,请告诉我,我会尝试更详细地说明

最佳答案

问题出在查询上。而不是

# comparing it with wishlist pk instead of wishlist's pro
Review.objects.filter(product_id=obj.id).count()

但它应该得到产品审查

def get_review(self, obj):
    return Review.objects.filter(product_id=obj.product.id).count()

关于python - 从另一个模型向序列化器添加额外的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083066/

相关文章:

python - 意外错误 : replace() takes 2 positional arguments but 3 were given

python - Python3 类型和 mypy 的意外可选行为

python - .join() 在 python 中给出返回列表

python - 如何为 tastypie 设置授权 header ?

python - 无法使用 instabot 登录

django - 如何在 django 中将图像添加到帖子中

javascript - 如何在 wagtail richtextfiled 中添加自定义类

python - 如何创建椭圆形几何体

python - 使用请求抓取动态页面

python - 未捕获 PyGame KEYDOWN 事件