Fin*_*ish 12 django many-to-many django-models django-views
我已经简化了我的模型,以便更清楚我想要做的事情.
(应用团队中的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
Run Code Online (Sandbox Code Playgroud)
(应用文档中的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
Run Code Online (Sandbox Code Playgroud)
我想要实现的是获得与文档相关联的用户列表,首先获得与文档关联的所有团队,然后从中获取与这些团队关联的所有用户.
到目前为止,我的尝试都是这样的
(应用文档中的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
....
Run Code Online (Sandbox Code Playgroud)
错误: 'QuerySet'对象没有属性'users'
associated_users = current_document.items.all().users.all()
Run Code Online (Sandbox Code Playgroud)
错误: 'QuerySet'对象没有属性'users'
associated_users = current_document.items.users.all()
Run Code Online (Sandbox Code Playgroud)
错误: 'ManyRelatedManager'对象没有属性'users'
我是以错误的方式来做这件事的吗?
Dan*_*man 16
嗯,是.current_document.teams.all()是一个查询集 - 或多或少,一个列表 - 团队.请求没有意义current_document.teams.all().users,因为查询集本身没有'users'属性,因此错误.users是每个团队元素的属性内该查询集.因此,执行此操作的一种方法是遍历查询集并请求与每个团队关联的用户.
然而,这将是无可救药的低效率 - 每个团队的一个数据库调用.更好的方法是直接询问数据库:向我提供与当前文档关联的团队中的所有用户.像这样:
User.objects.filter(team__documents=current_document)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13643 次 |
| 最近记录: |