2013-02-16 57 views
1

訪問我有一個MySQL表使用一個名爲UserProfile類,另一個使用名爲Connection類創建。我寫了下面的代碼來獲取一個用戶每發送一個連接請求,並把目標的名稱爲一個字符串:Django的經理無法通過實例

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 

我在做什麼錯了?過去我寫過類似的代碼,沒有任何問題。

+0

你的'UserProfile'和'Connection'模型是什麼樣的?請編輯您的問題並添加這些模型的源代碼。 – 2013-02-16 00:24:16

+0

使用用戶配置,相同的名稱爲模型定義,迭代是不是一個好的做法。 – iMom0 2013-02-16 00:28:17

+0

@ iMom0:謝謝你讓我知道。 – 2013-02-16 23:09:02

回答

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 
+0

它正在像一個魅力。謝謝。 – 2013-02-16 01:01:13

+0

還不行。 – 2013-02-16 23:09:48