Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将关系从M2O向后追溯到O2O?_Python_Django_Django Models_Django Templates - Fatal编程技术网

Python 如何将关系从M2O向后追溯到O2O?

Python 如何将关系从M2O向后追溯到O2O?,python,django,django-models,django-templates,Python,Django,Django Models,Django Templates,UserProfile具有一对一对“用户”和多对一对Place class UserProfile( models.Model ) : user = models.OneToOneField( User ) place = models.ForeignKey( Place, null = True, blank = True ) 在我的地点的详细视图中,我想列出该地点的所有居民。换句话说,我想列出所有Users,它们的UserProfile具有指定的Place 在我的模板中,

UserProfile
具有一对一对“用户”和多对一对
Place

class UserProfile( models.Model ) :
    user  = models.OneToOneField( User )
    place = models.ForeignKey( Place, null = True, blank = True )
在我的
地点
的详细视图中,我想列出该
地点
的所有居民。换句话说,我想列出所有
User
s,它们的
UserProfile
具有指定的
Place

在我的模板中,我尝试了

{% for resident in place.user_profile_set.user_set.all %}

但那没用。我想我在Django的概念中遗漏了一些基本的东西?

下面的东西呢:

{% for resident in place.userprofile_set.all %}
    {{ resident.user }}
{% endfor %}

下面的例子怎么样:

{% for resident in place.userprofile_set.all %}
    {{ resident.user }}
{% endfor %}

你错过了两件事,是的

第一个是从
Place
UserProfile
的向后关系是
UserProfile\u set
,而不是
user\u profile\u set

第二,从那里到
User
根本不是向后的关系:它是向前的,因为FK是在
UserProfile
模型上定义的。因此,从
UserProfile
User
,您只需执行
.User
——它是单个元素,而不是查询集


因此,正如pastylegs所说,您在
place.userprofile\u set.all
和do
profile.user
中迭代配置文件,是的,您缺少两件事

第一个是从
Place
UserProfile
的向后关系是
UserProfile\u set
,而不是
user\u profile\u set

第二,从那里到
User
根本不是向后的关系:它是向前的,因为FK是在
UserProfile
模型上定义的。因此,从
UserProfile
User
,您只需执行
.User
——它是单个元素,而不是查询集


因此,正如pastylegs所说,如果您有一个包含许多模板和.py源代码的大型项目,那么您可以在
place.userprofile\u set.all
和do
profile.user

中迭代配置文件。好主意是使用它来分析查询(运行时)可能很困难。好主意是使用它来分析查询可能很困难(运行时间)如果您有一个包含许多模板和.py源代码的大型项目。Duh,对。
UserProfile
to
User
是向前的哈哈。感谢您的详细解释!Duh,对。
UserProfile
to
User
是向前的哈哈。感谢您的详细解释!