【问题标题】:adding additional fields to serializer from another model从另一个模型向序列化程序添加附加字段
【发布时间】:2019-09-24 14:53:36
【问题描述】:

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

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
        }

但我对 product: 1 有一条评论,它应该显示 1 但它显示 0 我不知道我在这里缺少什么。请问有什么帮助吗?如果问题不清楚,请告诉我,我会尽量详细说明

【问题讨论】:

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


    【解决方案1】:

    问题在于查询。而不是

    # 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()
    

    【讨论】:

      【解决方案2】:

      我会使用.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 中的查询集上进行注释。我会覆盖get_queryset

      【讨论】:

        猜你喜欢
        • 2021-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 2021-04-15
        相关资源
        最近更新 更多