Django管理器无法通过实例访问

时间:2013-02-16 00:17:40

标签: mysql django

我有一个使用名为UserProfile的类创建的MySQL表,另一个使用名为Connection的类创建。我编写了以下代码来检索一个用户发送的每个连接请求,并将目标名称转换为字符串:

allprofiles = UserProfile.objects.all()

for UserProfile in allprofiles:
    userconnections = Connection.objects.filter(source_user=UserProfile)
    for Connection in userconnections:
        toplay = Connection
        target_tostring = toplay.target_user
        print target_tostring

但是当我尝试运行它时,Django显示以下内容:

AttributeError                            Traceback (most recent call last)
<ipython-input-6-323348f76c1f> in <module>()

      1 for UserProfile in allprofiles:
----> 2         userconnections = Connection.objects.filter(source_user=UserProfile)
      3         for Connection in userconnections:
      4                 toplay = Connection
      5                 target_tostring = toplay.target_user

/usr/lib/python2.7/dist-packages/django/db/models/manager.pyc in __get__(self, instance, type)

    209     def __get__(self, instance, type=None):
    210         if instance != None:
--> 211             raise AttributeError("Manager isn't accessible via %s instances" % type.__name__)
    212         return self.manager
    213 

AttributeError: Manager isn't accessible via Connection instances

我做错了什么?我过去写过类似的代码没有任何问题。

1 个答案:

答案 0 :(得分:4)

您正在覆盖UserProfileConnection个班级。换句话说,您将使用数据库中的数据替换模型类。请改用以下内容:

for user_profile in UserProfile.objects.all():
    for user_connection in Connection.objects.filter(source_user=user_profile):
        print user_connection.target_usr