1

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

9
  • what is the output you get when you print posts[0].author.user.username? Commented Aug 24, 2014 at 5:44
  • It should be select_related('author__user') if you want to prefetch the author information, but that alone shouldn't prevent you from doing e.g. posts[0].author.user.username as select_related is an optimization only. Commented Aug 24, 2014 at 5:49
  • oh, sorry! i got the right username! but my problem is accessing username after serializing "posts" can u help me with that ? does posts[0].author.user.username hit database again ? Commented Aug 24, 2014 at 5:52
  • Look into Serializing Django objects Commented Aug 24, 2014 at 5:56
  • thank u @Imc ! please answer "does posts[0].author.user.username hit database again ?" Commented Aug 24, 2014 at 6:05

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.