首页 > 解决方案 > 相关模型的 Django 查询

问题描述

我有这两个模型,产品和评论。

class Product(VoteModel, models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=False,
                             on_delete=models.CASCADE, related_name="%(class)s_listings")
    product_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False)
    product_title = models.CharField(max_length=150, null=False)
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True, auto_now_add=False)
    product_description = tinymce_models.HTMLField()
    num_vote = models.IntegerField(default=0)

评论模型

class Comment(VoteModel, models.Model):
        user        = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, blank=True, on_delete=models.SET_NULL)
        created_at     =  models.DateTimeField(auto_now=False, auto_now_add=True)
        updated_at     = models.DateTimeField(auto_now=True)
        ip_address = models.GenericIPAddressField(_('IP address'), unpack_ipv4=True, blank=True, null=True)
        rating = models.CharField(max_length=3, default=1.0)
         # Content-object field
        content_type = models.ForeignKey(ContentType,
                                         verbose_name=_('content type'),
                                         related_name="content_type_set_for_%(class)s",
                                         on_delete=models.CASCADE)
        object_pk = models.TextField(_('object ID'))
        content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk")

然后,我有一个序列化程序,我试图在其中获得评论的评级,以得出每个项目的平均评级

class ProductSerializer(ModelSerializer):
    product_rating = SerializerMethodField(read_only=True)

    class Meta:
        model = Product
        fields = [
            "product_rating"
        ]
        
   def get_product_rating(self, obj):

        comments = Comment.objects.filter(object_pk=obj.pk, content_type=ContentType.objects.get_for_model(obj))

        ....

        return {'rating': str(float("%.1f" % average)), 'views': views}

这似乎正在创建重复查询

评论 = Comment.objects.filter(object_pk=obj.pk, content_type=ContentType.objects.get_for_model(obj))

如何更好地重写查询以避免重复查询?这是视图,有点长:

class ProductsListAPIView(ListAPIView):
    model = Product

    serializer_class = ProductSerializer
    filter_backends = [SearchFilter, OrderingFilter]
    permission_classes = [HasAPIKey | AllowAny]
    search_fields = ['product_title', 'product_description',
                     'user__first_name', 'product_type', 'product_price', 'product_city']
    pagination_class = ProductPageNumberPagination
  ....
   queryset_list = Product.objects.active().filter(lookups).distinct(
            ) if query and len(query) > 0 else Product.objects.active()

        return queryset_list

标签: django

解决方案


推荐阅读