Dan
Dan

Reputation: 970

Django - serialize to JSON, how to serialize a FK User object

I'm on a page which sends a request to server side for a list of comments of current topic.

like this

localhost:8000/getComments/567 , while 567 is the topic id.

then, in my django view, like this:

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)

Now , the question is , when I try to use jQuery.parseJSON(data) at the browser side.

[
 {
   "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
   }
 } ..

I need to use some detail information of user object. (user is a Foreign Key in model PrjComment) such as user.first_name to display on the comment list.

but here it is only an id for user.("user": 33) How can I do that? Anyone who can kind help? Thank you very much

the User is the Django auth_user.

Upvotes: 2

Views: 1540

Answers (1)

Gevious
Gevious

Reputation: 3252

The easy solution would be to specify the values you need:

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

Update:

To access your userprofile information use the table name as defined in your AUTH_PROFILE_MODULE setting. In my case the table is called userprofile, and I'd access the data like this:

values('user__userprofile__moreinfo')

where moreinfo is the field you're interested in

Upvotes: 3

Related Questions