K
K
kuznetsovin2014-02-26 16:50:30
Django
kuznetsovin, 2014-02-26 16:50:30

Why doesn't select_related() work in Django 1.6?

There are models in which there are fields:

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, primary_key=True, unique=True, related_name='user_id')
    ...

class Comments(MPTTModel):
    ...
    user = models.ForeignKey(Profile, related_name='id_user_com')
    ...

When trying to request a username from the Comment model, an error is displayed that there is no such attribute:
c = Comments.objects.select_related('id_user_com__user_id').get(id=4)
print c.username

AttributeError: 'Comment' objects has no attribute 'username'

Tell me, please, I'm doing it wrong.
Ultimately, I need to serialize this request:
serializers.serialize('json', c, fields=('id','text','level','rating','username'))

Perhaps there is another way to get the username instead of its id.
Thanks in advance for your replies.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey K, 2014-02-26
@kuznetsovin

Access remains the same: c.user.username
select_related doesn't add fields to models, it just does the necessary joins

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question