13

我已经简化了我的模型,以使我想要做的事情更清楚。

(应用团队中的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

    ....

错误: “QuerySet”对象没有“用户”属性

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

错误: “QuerySet”对象没有“用户”属性

associated_users = current_document.items.users.all()

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

我会以错误的方式解决这个问题吗?

4

1 回答 1

17

嗯,是。current_document.teams.all()是一个查询集 - 或多或少是一个团队列表。要求 是没有意义的current_document.teams.all().users,因为查询集本身没有“用户”属性,因此会出现错误。users是该查询集中每个 Team 元素的属性。因此,一种方法是遍历查询集并询问与每个团队关联的用户。

然而,这将是非常低效的——每个团队调用一次数据库。更好的方法是直接询问数据库:给我与当前文档相关联的团队中的所有用户。像这样:

User.objects.filter(team__documents=current_document)
于 2012-04-18T19:01:39.923 回答