Bheid
Bheid

Reputation: 307

Django Query or SQL

I have these models:

class Person(models.Model):
    user = models.OneToOneField(User)

class Post(models.Model):
    author = models.ForeignKey(Person, null=False)
    text = models.TextField(null=False, blank=False)

and want a Queryset at least with the below fields,

author.user.username
text

I have read select_related() queries but when I try to use that with this view can't get username field

posts = Post.objects.select_related('person__user')[:10]

can I use Django query or have to use SQL raw ?

Thanks for any help

Upvotes: 1

Views: 169

Answers (2)

ruddra
ruddra

Reputation: 51948

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)

Upvotes: 2

Josh Smeaton
Josh Smeaton

Reputation: 48710

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).

Upvotes: 0

Related Questions