【问题标题】:How follow a relationship backward from a M2O to O2O?如何遵循从 M2O 到 O2O 的关系?
【发布时间】:2012-03-30 10:30:28
【问题描述】:

UserProfile 与“用户”是一对一的,与Place 是多对一的

class UserProfile( models.Model ) :
    user  = models.OneToOneField( User )
    place = models.ForeignKey( Place, null = True, blank = True )

Place 的详细视图中,我想列出该Place 的所有居民。换句话说,我想列出所有Users,其UserProfile 具有指定的Place

在我的模板中,我尝试过

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

但这没有用。我想我在 Django 的 "following a relationship backwards" 概念中缺少一些基本的东西?

【问题讨论】:

  • 好主意是使用related_name
  • 如果您有一个包含许多模板和 .py 源代码的大型项目,则可能很难对您的查询(运行时间)进行任何处理。

标签: python django django-models django-templates


【解决方案1】:

你错过了两件事,是的。

首先是PlaceUserProfile的反向关系是userprofile_set,而不是user_profile_set

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

因此,正如pastylegs 所说,您遍历place.userprofile_set.all 中的配置文件并执行profile.user

【讨论】:

  • 呃,对。 UserProfileUser 是转发哈哈。感谢您的详细解释!
【解决方案2】:

类似以下的内容呢:

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

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2019-06-03
    • 2017-10-26
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多