Django 复杂查询通过数据库 API

Django complex Query through database API

我正在使用 django 1.7,python 3.4 我有一个名为 'EnterpriseProfile' 的模型 class,它与名为 'Enterprise' 的 class 是一对一的关系。还有另一个模型 'User' 与 'Enterprise' 有多对多的关系。现在,在 'EnterpriseProfile' 模型中,我想创建一个 returns 与该企业相关的所有用户的功能。 通过 django 数据库 API 或使用原始 SQL 查询实现此目的的最佳方法是什么。

有些代码会有所帮助,但我相信在 EnterpriseProfile 中执行此操作

注意:这取决于您如何命名某些字段。

您不需要函数:

profile = EnterpriseProfile.objects.get(pk=1)  # or whatever to get the object
# next returns all users related to that enterprise in the M2M
profile.enterprise.users.all()