【发布时间】:2019-03-08 18:42:29
【问题描述】:
我有以下形式的数据:
collection_name | type | manufacturer | description | image_url
---------------------------------------------------------------------------
beach | bed | company a | nice bed | 1.jpg
beach | king bed | company a | nice bed | 1.jpg
beach | nightstand | company a | nice ns | 1.jpg
grass | chest | company a | nice chest | 2.jpg
apple | chest | company a | nice chest | 3.jpg
fiver | chest | company b | good chest | 4.jpg
以及类似的模型:
class Product(models.Model):
collection_name = models.TextField(null='true',blank='true')
type = models.TextField(null='true',blank='true')
manufacturer = models.TextField(null='true',blank='true')
description = models.TextField(null='true',blank='true')
image_url = models.TextField(null='true',blank='true')
我目前在我的应用中尝试做的是:
- 通过 id 链接到产品(使用隐藏的 pk id 字段),
- 然后为该 id 获取集合名称
- 获取具有该集合名称的产品列表
- 从具有特定集合名称的产品集中获取不同的 image_url 列表 *
- 对于新集合中的每个image_url,获取所有具有相同image_url的记录
我想这样做的原因是,正如您在上面的示例数据中看到的那样,不同的产品有时会重复使用同一张图片(有些图片在一张图片中显示多个产品)。我只想显示每张图片一次,同时能够显示与给定图片相关的所有产品(其中可能有多个)。
我一直在考虑根据this 的答案做以下类似的事情,我认为它遵循上面给出的逻辑,但我不确定这是正确的方法。
collectionname = product.objects.filter(id=id).values('collection_name').distinct()
images = product.objects.filter(collection_name__in=collectionname).values("image_url").distinct()
results = []
for img in images:
pbis = product.objects.filter(collection_name__in=collectionname, image_url=img['image_url'])
obj = {"image": img['image_url'], "items":[{"attr":pbi.attr, ...} for pbi in pbis]}
results.append(obj)
我的方法中有哪些明显的错误,是否有更好、更简洁的方法来做到这一点?如果相关,后端是 postgres。
我希望能够在模板中做的事情是这样的:
{% for instance in image_url %}
{{ collection_name }} Collection:
<img src="{{ instance }}">
Product type: {{ instance.type }}
Product Description: {{ instance.description }}
{% endfor %}
应该输出如下内容:
对于 1.jpg:
Beach Collection
<img src="1.jpg">
Product type: bed
Product Description: nice bed
Product type: king bed
Product Description: nice bed
Product type: nightstand
Product Description: nice ns
对于 2.jpg:
Grass Collection
<img src="2.jpg">
Product type: chest
Product Description: nice chest
对于 3.jpg:
Apple Collection
<img src="3.jpg">
Product type: chest
Product Description: nice chest
对于 4.jpg:
Fiver Collection
<img src="4.jpg">
Product type: chest
Product Description: good chest
【问题讨论】:
标签: django