Yco*_*con 3 python django postgresql django-orm django-rest-framework
我正在配置一个 API 来提取结果列表。这些物品是服装“产品”,有多种“变体”。
我试图使用unique来确保查询集仅返回唯一产品的列表 - 而不是由于许多变化而重复多次的同一产品。
过去,我在产品的主键(id)上使用了distinct。但是,下面的代码不起作用。
当我尝试使用“distinct”时,出现 500 错误。没有它-我不会得到任何错误。我无法在本地测试,因为 SQLite 不喜欢不同的。我在用
class InternalListView(APIView):
renderer_classes = (JSONRenderer, )
def get(self, request, *args, **kwargs):
filters = {}
for key, value in request.GET.items():
key = key.lower()
if key in countmatch:
lookup, val = internalmatch[key](value.lower())
filters[lookup] = val
qset = (
Product.objects
.filter(**filters)
.distinct('id')
.order_by('-rating')
.values('name', 'brand', 'rating')
.annotate(
price=F('variation__price__price'),
id=F('pk'),
vari=F('variation'),
)
)
for i in qset:
i['likes'] = random.randint(500, 1000)
print qset
return Response(qset.all())
Run Code Online (Sandbox Code Playgroud)
啊啊刚刚想通了。
根据 django 文档(https://docs.djangoproject.com/en/1.9/ref/models/querysets/#distinct)
unique 和 order_by 必须相同。
所以这不起作用:
.distinct('id')
.order_by('-rating')
Run Code Online (Sandbox Code Playgroud)
但这会起作用:
.distinct('id')
.order_by('id')
Run Code Online (Sandbox Code Playgroud)
这效果最好:
.distinct('rating', 'id')
.order_by('-rating')
Run Code Online (Sandbox Code Playgroud)
使用选项3有什么问题吗?
| 归档时间: |
|
| 查看次数: |
2229 次 |
| 最近记录: |