2012-04-18 141 views
10

我简化了我的模型,使其更加清晰,我试图做的更清楚。Django:通过另一个多对多关系访问多对多对象

(在应用程序团队models.py)

from django.db import models 
from django.contrib.auth.models import User 
import datetime 

class Team(models.Model): 
    users = models.ManyToManyField(User) 
    team_title = models.CharField(max_length=200) 
    team_description = models.CharField(max_length=200) 

    def __unicode__(self): 
     return self.team_title 

(在应用程序文件models.py)

from django.db import models 
import datetime 

class Document(models.Model):  
    teams = models.ManyToManyField("Teams.Team", blank=True) 
    document_title = models.CharField(max_length=200) 
    document_description = models.TextField() 

def __unicode__(self): 
    return self.document_title 

我想实现的是让谁已与相关用户列表首先获取与文档相关的所有团队,然后从中获取与这些团队相关的所有用户。

我尝试至今都走了这样的事情

(在应用程序文件view.py)

from django.contrib.auth.models import User 
from Documents.models import * 
from Teams.models import * 

def docUsers(request, doc_id): 
    current_document = Documents.objects.get(pk = doc_id) 
    associated_users = current_document.teams.all().users 

    .... 

错误: '查询集' 对象有没有属性 '用户'

associated_users = current_document.items.all().users.all() 

错误:'QuerySet'对象没有属性'users'

associated_users = current_document.items.users.all() 

错误: 'ManyRelatedManager' 对象有没有属性 '用户'

我要对这个错误的方式?

回答

13

好的,是的。 current_document.teams.all()是一个查询集 - 或多或少是一个列表 - 团队。请求current_document.teams.all().users没有任何意义,因为查询集本身不具有“用户”属性,因此是错误。 users是查询集中内的每个Team元素的属性。因此,一种做法是遍历查询集并询问与每个团队相关的用户。

但是,这将是无望的低效率 - 每个团队一个数据库调用。更好的方法是直接询问数据库:给我所有与当前文档相关的团队的用户。像这样:

User.objects.filter(team__documents=current_document) 
+1

我还是很困惑。团队模型与文档模型的关联是从文档到团队,而不是其他方式(我知道这不是最合理的方法,但我不允许更改模型结构),那么如何过滤team__文档? – Finglish 2012-04-18 20:44:33

+1

@agf 1.不,您使用过滤器表达式中的实际模型名称。 2.不,您使用=在M2M/FK关系中查找单个元素。请参阅[跨越关系的查找](https://docs.djangoproject.com/en/1.3/topics/db/queries/#lookups-that-span-relationships)。 – 2012-04-18 20:55:19

+0

@英国人,你可以访问双方的关系。看到我给agf的链接。 – 2012-04-18 20:55:42