django - 相关模型的 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
解决方案
推荐阅读
- delphi - 如何处理浮点数逼近?
- loops - Clojure - 使用循环递归的斐波那契 - 进入无限循环
- postgresql - 夏季和冬季 postgres 时区/时间戳
- javascript - 用 pg-promise 中断一个长事务
- java - 输入不匹配异常错误?
- c++ - 没有 return 语句的函数中的 c++ 返回什么?
- c# - 将 C# 代码转换为 PHP:创建空字节数组 php 并使用套接字发送
- xamarin.ios - 适用于 Xamarin 的 Mac Mini
- php - 通过改造在文件上传期间关闭 Smack 连接
- apache-spark - Apache spark - 窗口函数,FIRST_VALUE 不起作用