0

我用select_related,查询日志很好。

如何使用上下文变量“帖子”?

{{post.username}}不管用。

模型.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)

视图.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

模板.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>        

查询集查询

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;
4

1 回答 1

2

您可以使用:

{{ post.created_by.username }}

而不是{{ post.username }}. 因为 Post 模型没有任何名为username. 由于有一个名为User模型的 ForiegnKey ,并且created_byUser一个名为 的字段,因此您可以通过.usernamepost.created_by.username

更新

如果你annotate是一个新变量username,那么你可以使用post.username. 您可以像这样注释您的查询集:

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
于 2019-06-19T02:48:23.583 回答