从其他模型向序列化器添加其他字段

时间:2019-09-24 14:53:36

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

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

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我不知道我在这里缺少什么。有什么帮助吗?如果问题不清楚,请告诉我,我将尝试更详细地说明

2 个答案:

答案 0 :(得分:0)

我会使用.annotate

from django.db.models import Count

WishList.objects.annotate(review_count=Count('product__review_set')

检查要用于产品审查的相关名称,但如果未定义,则应为review_set

然后将'review_count'添加到WishListSerializer字段。

review_count = serializers.IntegerField(required=False)

您将在ViewSet中的queryset上进行注释。我会覆盖get_queryset

答案 1 :(得分:0)

问题出在查询上。代替

TimerManager

但是它应该得到产品的评论

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