gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:39:08 26 4
gpt4 key购买 nike

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

在 SQL 中我们可以这样写:

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

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

Cannot resolve keyword 'phonenumber' into field

我什至尝试过 select_lated 但没有用。我做错了什么吗?

模型.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

最佳答案

phonenumberperson上的一个字段,所以需要传入person__phonenumber

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

关于Django模型外键查询集选择相关字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5380529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com