【发布时间】:2014-08-26 15:44:55
【问题描述】:
我有一张像这样的桌子
class Person(User):
"""
This model represents person's personal and
professional details.
"""
attribute1 = models.CharField(max_length=100)
attribute2 = models.TextField()
attribute3 = models.TextField()
attribute4 = models.ForeignKey(Receptionist)
referred_attribute1 = models.ManyToManyField(Hobby)
class Hobby(models.Model):
name = models.CharField(max_length=100)
用例: Person P1 有 Hobbies h1,h2,h3(在 Hobby 表中定义[作为 3 个单独的条目])。 现在我想检索一个 Person 对象,该对象具有它所具有的所有属性和属性,包括爱好。为此,我正在执行以下操作:
Person.objects.values("attribute1",
"attribute2",
"referred_attribute1").get(attribute3="p1's attribute")
我想要的是:
{'attribute1':'p1_attribute1',
'attribute2':'p1_attribute2',
'referred_attribute':['h1','h2','h3']}
我得到的是:
[{'attribute1':'p1_attribute1',
'attribute2':'p1_attribute2',
'referred_attribute':'h1'},
{'attribute1':'p1_attribute1',
'attribute2':'p1_attribute2',
'referred_attribute':'h2'},
{'attribute1':'p1_attribute1',
'attribute2':'p1_attribute2',
'referred_attribute':'h3'}]
有没有办法直接从查询集中获得我想要的结果?因为我不想手动重新排列上面的结果!
【问题讨论】:
-
这不是一个直接的答案,只是一个建议:对多对多关系使用不同的查询,然后加入它。
-
“使用不同的查询”- 你能详细说明一下吗?
标签: django django-models django-queryset django-orm