[Answered ]-Django Query or SQL

2👍

You can serialize like this:

import json
from django.core.serializers.json import DjangoJSONEncoder
json_data = json.dumps(list(Post.objects.values('author__user__username', 'text')[:10]), cls=DjangoJSONEncoder)
👤ruddra

0👍

select_related should be called with the field names, not the type.

posts = Post.objects.select_related('author__user')[:10]  
for post in posts:
    print(post.person.user.username)
    print(post.text)

All the select_related does is ensure that the foreign fields can be accessed without extra queries (select_related constructs joins to the relevant tables).

Leave a comment