[Fixed]-Get only certain fields of related object in Django

16πŸ‘

If you want to have comments with some additional user data, without having to retrieve whole User objects I believe it’s better to fetch additional data when you fetch the comments:

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

Obviously you can fetch other useful Comment fields.

OR:

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

This still uses the QuerySet API, but both approaches allow you to span relationships to get additional data without extra queries.

πŸ‘€Ivan

1πŸ‘

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

That should do

πŸ‘€Otuoma Sanya

1πŸ‘

queryset = ModelName.objects.filter().only('realed_obj__field1', 'related_obj__field2')

0πŸ‘

It must be equal to select name, email from users where id=comment.user_id by complexity.

What is really equivalent to this query is what you already have:

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

… but values_list only applicable to QuerySet object, not to model instance.

That is absolutely right. but what you need to consider is that once you have this queryset you can get the first element because with one user id there will just be one user:

name, email = Users.objects.filter(id=comment.user_id).values_list('name', 'email').first()
πŸ‘€AKS

Leave a comment