Get only specific fields of a related object in Django

Let's say I have such models in Django:

class User(models.Model):
    name=models.CharField(...)
    email=models.EmailField(...)
    photo=...
    <other fields>

class Comment(models.Model):
    user=models.ForeignKey(User, ...)

I have a function that receives a Comment object and requires only the name and email fields to send email (this is just an example, obviously)

def sendEmail(comment):
    name, email=comment.user.name, comment.user.email

In the implementation presented above, Django will retrieve all the fields of the associated User object (approximately equal select * from users where id=comment.user_id) Using values_list, I can get only the necessary fields:

Users.objects.filter(id=comment.user_id).values_list('name', 'email')

but values_list applies only to the QuerySet object, not to the model instance. My question is: is there a way to do the same using only the "comment" object? It should be equal select name, email from users where id=comment.user_idin complexity (I do not want to transfer a lot of data stored in some fields over the network when I do not need it)

+4
2

, User, , :

Comment.objects.filter(user=user).values_list('user__name', 'user__email')

, Comment.

Comment.objects.filter(user=user).annotate(author_name=F('user__name'),\ 
                                           author_email=F('user__email'))

API QuerySet, .

+2

select name, email from users where id=comment.user_id .

, , - , :

Users.objects.filter(id=comment.user_id).values_list('name', 'email')

... values_list QuerySet, .

. , , , :

name, email = Users.objects.filter(id=comment.user_id).values_list('name', 'email').first()
0

Source: https://habr.com/ru/post/1663539/


All Articles