django模型外键查询集选择相关字段

时间:2011-03-21 16:25:25

标签: django django-models

我正在尝试从DJango中两个相关表的连接中进行选择,如下所示。但是我无法获得另一个表的字段name

在SQL中我们可以写:

select person.phonenumber,membership.* from membership where person=name ;

这会显示所有membership字段以及phonenumber,但在Django中会抛出错误:

  

无法将关键字“phonenumber”解析为字段

我甚至尝试使用select_related但没有用。我做错了吗?

model.py:

from django.db import models

# Create your models here.
class Person(models.Model):
    name = models.CharField(primary_key=True,max_length=128)
    phonenumber = models.CharField(max_length=128)
    city = models.CharField(max_length=128)


    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)


>>> print m.query
SELECT `myapp_membership`.`id`, `myapp_membership`.`person_id`, `myapp_membership`.`date_joined`, `myapp_membership`.`invite_reason` FROM `myapp_membership` WHERE `myapp_membership`.`person_id` = x 
>>> m=Membership.objects.filter(person__name='x').select_related()
>>> print m.query
SELECT `myapp_membership`.`id`, `myapp_membership`.`person_id`, `myapp_membership`.`date_joined`, `myapp_membership`.`invite_reason`, `myapp_person`.`name`, `myapp_person`.`phonenumber`, `myapp_person`.`city` FROM `myapp_membership` INNER JOIN `myapp_person` ON (`myapp_membership`.`person_id` = `myapp_person`.`name`) WHERE `myapp_membership`.`person_id` = x 
>>> m=Membership.objects.filter(person__name='x').values('person','phonenumber').select_related()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/query.py", line 510, in values
    return self._clone(klass=ValuesQuerySet, setup=True, _fields=fields)
  File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/query.py", line 766, in _clone
    c._setup_query()
  File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/query.py", line 889, in _setup_query
    self.query.add_fields(self.field_names, False)
  File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/sql/query.py", line 1537, in add_fields
    "Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'phonenumber' into field. Choices are: date_joined, id, invite_reason, person

2 个答案:

答案 0 :(得分:19)

phonenumberperson上的字段,因此您需要传入person__phonenumber

m=Membership.objects.filter(person__name='x').values('person','person__phonenumber').

答案 1 :(得分:3)

另外,如果你想要一个查询集(所以不要使用值),你可以这样做:

m=Membership.objects.filter(person__name="x").select_related('person', depth=1)

可悲的是,我不知道如何只从该表中获取一个字段并仍然获得一个查询集。