python - 如何将关系从 M2O 倒推到 O2O?

标签 python django django-models django-templates

UserProfile 与“User”一对一,与 Place 多对一

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

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

在我的模板中,我试过了

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

但这没有用。我想我在 Django 的 "following a relationship backwards" 概念中从根本上遗漏了一些东西?

最佳答案

是的,你错过了两件事。

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

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

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

关于python - 如何将关系从 M2O 倒推到 O2O?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9941276/

相关文章:

javascript - 如何将 jQuery 变量设置为 django 模板变量

python - Django ORM - 过滤相关对象

python - 使用 setattr 添加的属性未显示在 help() 中

python - 如何在我的项目中安装 django-scheduler。我收到一条错误消息,指出无法导入模块

python - Django 属性错误

python - 如何在forms.py和views.py中创建子类字段时更改父类中的字段?

python - django 覆盖模型表单或字段中的默认错误消息

python - 对 admin.py 的更新未反射(reflect)在 django 管理页面中

python - 确定数组中的重复值

python - 选择列与列表中的元素匹配的行 SQLAlchemy