0

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;
Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48

1 Answers1

2

You can use:

{{ post.created_by.username }}

instead of {{ post.username }}. Because Post model does not have any field named username. As there is a ForiegnKey named created_by to User model, and User has a field named username, so you can access it via post.created_by.username.

Update

If you annotate a new variable username, then you can use post.username. You can annotate your queryset like this:

from django.db.models import F
class PostListView(LoginRequiredMixin, ListView):
    context_object_name = 'posts'

    def get_queryset(self):
        queryset = Post.objects.select_related('created_by').annotate(username=F('created_by__username')).order_by('-id')
        return queryset
ruddra
  • 50,746
  • 7
  • 78
  • 101