Skip to main content
 首页 » 编程设计

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

2025年05月04日17www_RR

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" 概念中从根本上遗漏了一些东西?

请您参考如下方法:

是的,你错过了两件事。

首先,从Place到UserProfile的反向关系是userprofile_set,而不是user_profile_set。

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

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