我简化了我的模型,使其更加清晰,我试图做的更清楚。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' 对象有没有属性 '用户'
我要对这个错误的方式?
我还是很困惑。团队模型与文档模型的关联是从文档到团队,而不是其他方式(我知道这不是最合理的方法,但我不允许更改模型结构),那么如何过滤team__文档? – Finglish 2012-04-18 20:44:33
@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
@英国人,你可以访问双方的关系。看到我给agf的链接。 – 2012-04-18 20:55:42