I use select_related, and query log is good.
How can I use the context variables 'posts'?
{{post.username}}
is not working.
model.py
class Post(models.Model):
`subject = models.CharField(default='', max_length=255)
content = models.TextField(default='')
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
view.py
class PostListView(LoginRequiredMixin, ListView):
context_object_name = 'posts'
def get_queryset(self):
queryset = Post.objects.select_related('created_by').order_by('-id')
return queryset
template.html
<table>
<thead>
<tr>
<th >No.</th>
<th>subject</th>
<th>author</th>
<th>date</th>
</tr>
</thead>
<tbody>
{% for post in posts %}
<tr>
<th>{{ forloop.counter }}</th>
<td><a href="">{{ post.subject }}</a></td>
<td>{{ post.username }}</td> <!-- not work -->
<td>{{ post.created_at }}</td>
</tr>
{% endfor %}
</tbody>
</table>
queryset queries
SELECT `Posts`.`id`, `Posts`.`subject`, `Posts`.`content`, `Posts`.`created_at`, `Posts`.`created_by_id`, `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`, `auth_user`.`is_superuser`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`date_joined` FROM `Posts` INNER JOIN `auth_user` ON (`Posts`.`created_by_id` = `auth_user`.`id`) ORDER BY `Posts`.`id` DESC;