我有以下模型,其中填充了以下内容:
属性
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
.........................
我想在查询中获取此结果(在列表,字典,查询集的形式下,哪种形式无关紧要):
concept_id definition prefLabel scope
1 blablabla prefferedLabel Scopeee
2 another definition another label 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)
不确定这是否是最佳解决方案
答案 0 :(得分:1)
假设您的Property
模型有一个字段:models.ForeignKey('Concept', ...)
,您只需follow that relationship backwards:
# 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'])