【问题标题】:django select_related('created_by').... what is the context variables?django select_related('created_by')....什么是上下文变量?
【发布时间】:2019-06-19 02:45:38
【问题描述】:

我用select_related,查询日志不错。

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

{{post.username}} 不工作。

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>        

查询集查询

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;

【问题讨论】:

    标签: django django-select-related


    【解决方案1】:

    你可以使用:

    {{ post.created_by.username }}
    

    而不是{{ post.username }}。因为 Post 模型没有任何名为 username 的字段。由于User模型有一个名为created_by的ForiegnKey,而User有一个名为username的字段,所以你可以通过post.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

    【讨论】:

    • 太棒了。请考虑marking it as accepted 回答:)
    • 我可以更改变量名 'post.created_by.username' > 'post.username' ...我设置其他什么..?
    • 请参阅答案的更新部分。我提供了一种实现你想要的方法。
    猜你喜欢
    • 2014-01-24
    • 1970-01-01
    • 2014-08-15
    • 2019-07-28
    • 1970-01-01
    • 2017-01-24
    • 2019-03-23
    • 2014-12-06
    • 1970-01-01
    相关资源
    最近更新 更多