我需要使用不同的order_by&不同的值,我尝试使用子查询。
我怎样才能做到这一点?
qset可以选择我想要的产品,然后在单独的查询中,选择要显示其价格的15种变体吗?
换句话说:Qset随机选择产品ID(在查询集中),然后python告诉它返回这15个项目的查询集。
加速查询也很重要 - 因为需要大约800毫秒(当我通过pk命令时)或5.8秒时我使用order_by'?'。
我的尝试:
distinct_qs = (
Product.objects
.distinct('id')
)
qset = (
Product.objects
.filter(pk__in=distinct_qs)
.order_by('rating', '?')
.values('name', 'image',)
.annotate(
price=F('variation__price__price'),
id=F('pk'),
vari=F('variation'),
)[:15]
)
输出数据样本:
{"name":"Test Item","vari":10, id":1, "price":"80", "image":"xyz.com/1.jpg"},
{"name":"Test Item","vari":11, id":1, "price":"80", "image":"xyz.com/1.jpg"},
{"name":"Another one","vari":14, id":2, "price":"10", "image":"xyz.com/2.jpg"},
{"name":"Another one","vari":15, id":2, "price":"10", "image":"xyz.com/2.jpg"},
{"name":"And Again","vari":17, id":3, "price":"12", "image":"xyz.com/3.jpg"},
{"name":"And Again","vari":18, id":3, "price":"12", "image":"xyz.com/3.jpg"},
所需的输出数据:
{"name":"Test Item","vari":13, id":1, "price":"80", "image":"xyz.com/1.jpg"},
{"name":"Another one","vari":14, id":2, "price":"10", "image":"xyz.com/2.jpg"},
{"name":"And Again","vari":17, id":3, "price":"12", "image":"xyz.com/3.jpg"},
models.py
的示例class Product(models.Model):
name = models.CharField ("Name", max_length=400)
...
class Variation(models.Model):
product = models.ForeignKey(Product, db_index=True, blank=False, null=False)
...
class Image(models.Model):
variation = models.ForeignKey(Variation, blank=False, null=False)
image = models.URLField(max_length=540, blank=True, null=True)
class Price(models.Model):
price = models.DecimalField("Price", decimal_places=2, max_digits=10)
variation = models.ForeignKey(Variation, blank=False, null=False)
答案 0 :(得分:0)
我认为你应该编写一个自定义模型管理器(参见https://docs.djangoproject.com/en/1.9/topics/db/managers/)并在那里创建一个方法,然后用它来返回变体而不是标准查询。
对于随机化,您可以这样做: 选择Variation(或Product)的最后一个id,然后从该间隔生成不同的随机15 ID,然后从数据库中拉出带有这些id的对象。我认为它应该更快。