2011-12-12 56 views
2

我在一個頁面上向當前主題的評論列表發送一個請求到服務器端。Django - 序列化爲JSON,如何序列化一個FK用戶對象

這樣

本地主機:8000/getComments/567,而567是主題ID。

然後,在我的Django的觀點,這樣的:

def getProjectComments(request, pId): 
    format = 'json' 
    mimetype = 'application/javascript' #'application/xml' for 'xml' format 
    comments = PrjComment.objects.filter(prj=pId) 
    data = serializers.serialize(format, comments) 
    return HttpResponse(data,mimetype) 

現在的問題是, 當我嘗試在瀏覽器端使用jQuery.parseJSON(數據)。

[ 
{ 
    "pk": 10, 
    "model": "app.prjcomment", 
    "fields": 
    { 
     "status": 1, 
     "time_Commented": "2011-12-11 17:23:56", 
     "prj": 1, 
     "content": "my comment 1", 
     "user": 25 
    } 
    }, 
    { 
    "pk": 9, 
    "model": "app.prjcomment", 
    "fields": { 
    "status": 1, 
    "time_Commented": "2011-12-11 17:23:51", 
    "prj": 1, 
    "content": "comment \u4e00\u4e2a", 
    "user": 33 
    } 
} .. 

我需要使用用戶對象的一些細節信息。 (用戶是PrjComment模型中的外鍵) (如user.first_name)顯示在註釋列表中。

但這裏它只是一個用戶id(「user」:33) 我該怎麼做?任何人可以提供幫助嗎? 非常感謝你

用戶是Django的auth_user。

+0

最後的領域,我所用的原始SQL來實現此功能。 – Dan

回答

3

最簡單的解決辦法是指定您需要的值:

comments = PrjComment.objects.filter(prj=pId) \ 
        .values('status','time_commented','prj','content','user__id', 
          'user__username','user__first_name') 

更新:

要訪問您的用戶配置文件信息的使用在你的AUTH_PROFILE_MODULE設置中定義的表名。在我的情況下,表稱爲USERPROFILE,我會像這樣訪問的數據:

values('user__userprofile__moreinfo') 

其中moreinfo是你感興趣的

+0

非常感謝你,它適用於我,但這裏帶來另一個問題。我無法訪問filter()。values()中的'user.get_profile'。 user__first_name可以獲取first_name,但我無法獲取userprofile表中的用戶屬性。我試過user__get_profile,這對我不起作用。有什麼建議麼?謝謝。 – Dan

+0

如果您滿意,請將答案標記爲已接受。 – Gevious

+0

用戶配置文件仍然無法在settings.xml中工作AUTH_PROFILE_MODULE ='hedan.UserProfile'====> FieldError at/projects/morecomments/1/11 無法將關鍵字'user__UserProfile__telephone'解析爲字段。選項有:cId,內容,prj,回覆,狀態 – Dan