【发布时间】:2021-10-15 21:27:12
【问题描述】:
您好,帮助查询集的 values() 方法。显示相关字段(外键)时,数据重复,这个数据可以分组吗?
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True, db_index=True)
class ProductImage(models.Model):
product = models.ForeignKey(Product, related_name='product_image', on_delete=models.CASCADE)
image = models.ImageField(upload_to='img/models/')
is_main = models.BooleanField()
查看代码
data = Product.objects.all().values('pk', 'title', 'product_image')
此处为示例
这就是它的显示方式
[
{'pk': 1, 'title': 'Product 1', 'product_image__image': 'img/models/mod_wpYzlnm.png'},
{'pk': 2, 'title': 'Product 2', 'product_image__image': 'img/models/mod2_wEr0D2q.png'},
{'pk': 2, 'title': 'Product 2', 'product_image__image': 'img/models/mod_pPQqmjB_we175uR.png'},
{'pk': 10, 'title': 'Product 3', 'product_image__image': 'img/models/mod_3mTxkb9_z4lKV3l.png'},
{'pk': 10, 'title': 'Product 3', 'product_image__image': 'img/models/heart.png'}
]
应该是这样的
[
{'pk': 1, 'title': 'Product 1, 'product_image':[
{'image':'img/models/mod_wpYzlnm.png'}
]},
{'pk': 2, 'title': 'Product 2', 'product_image': [
{'image':'img/models/mod2_wEr0D2q.png'},
{'image':'img/models/mod_pPQqmjB_we175uR.png'}
]},
{'pk': 10, 'title': 'Product 3', 'product_image': [
{'image':'img/models/mod_3mTxkb9_z4lKV3l.png'},
{'image':'img/models/heart.png'}
]},
]
【问题讨论】:
-
当你做什么查询...?
-
data = Product.objects.all().values('pk', 'title', 'product_image')
-
我觉得很奇怪,如果有多个项目,则使用列表,但如果有一个则使用字符串。这会让“读者”的逻辑更加复杂。
-
对不起,是的,必须有一个列表
code {'pk': 1, 'title': 'Product 1, 'product_image':[ {'image':'img/models/mod_wpYzlnm.png'} ]},
标签: django