Django-如何进行此查询
我有以下模型,其中填充了如下内容: 属性Django-如何进行此查询,django,Django,我有以下模型,其中填充了如下内容: 属性 concept_id name value 1 definition blablabla 1 prefLabel prefferedLabel 1 scope Scopeee 1 NOT_NEEDED a not needed value 2 definit
concept_id name value
1 definition blablabla
1 prefLabel prefferedLabel
1 scope Scopeee
1 NOT_NEEDED a not needed value
2 definition another definition
2 prefLabel another label
2 scope another scope
.........................
我想在查询中获得这个结果(以列表、字典、查询集的形式,不管是哪种形式):
我怎样才能做到这一点?谢谢
编辑:我正在使用MySQL
我丑陋的解决方案就是这个
for concept_id in Concept.objects.all().values_list('id', flat=True):
Property.objects.filter(concept_id=concept_id, name__in=['prefLabel', 'scope', 'definition'])
.....
但是真的很难看,我想要一些不同的东西
pcoronel的解决方案:
table = []
for concept in Concept.objects.all():
row = {'code': concept.id}
result=concept.property_set.filter(
name__in=['prefLabel', 'scope', 'definition'],
)
for r in result:
row.update({
r.name: r.value,
})
table.append(row)
不确定这是否是最佳解决方案假设您的
属性
模型有一个字段:models.ForeignKey('Concept',…)
,您可以:
没什么…这只是我想要检索的输出。除了
定义
、预标签
和范围
之外,名称
列可能还有其他值,它们是这样连接的。让我试试看,成功了!我编辑了我的帖子,让每个人都能看到解决方案。然而,我想知道这是否是最优化的查询。
table = []
for concept in Concept.objects.all():
row = {'code': concept.id}
result=concept.property_set.filter(
name__in=['prefLabel', 'scope', 'definition'],
)
for r in result:
row.update({
r.name: r.value,
})
table.append(row)
# iterate through Concepts and get desired related Properties using their name
for concept in Concept.objects.all():
concept.property_set.filter(name__in=['prefLabel', 'scope', 'definition'])