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.
1π
Users.objects.filter(id=comment.user_id).values_list('name', 'email').get()
That should do
1π
queryset = ModelName.objects.filter().only('realed_obj__field1', 'related_obj__field2')
- Django REST framework β multiple lookup fields?
- ImportError: cannot import name "urandom"
- Relation does not exist error in Django
- Django rest auth email instead of username
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 toQuerySet
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()
- Celerybeat not executing periodic tasks
- How can I create an encrypted django field that converts data when it's retrieved from the database?
- Passing list of values to django view via jQuery ajax call
- Django global variable