【问题标题】:Django listview doesn't show the recent data added to the databaseDjango listview 不显示最近添加到数据库中的数据
【发布时间】:2020-09-03 09:58:26
【问题描述】:

由于某种原因,Listview 不会检索添加到数据库中的新数据。这是我的代码:

class UserThreadsListView(ListView):
    model = Thread
    template_name = 'tweetsview.html'
    paginate_by = 20
    context_object_name = 'threads_list'

    def get_context_data(self, **kwargs):
        context =  super(UserThreadsListView, self).get_context_data(**kwargs)
        responsible = ConciergeSpecialist.objects.get(id=self.kwargs['pk'])
        if self.request.user.is_superuser:
            context['teammates_list'] = ConciergeSpecialist.objects.all().exclude(active=False)
        else:
            context['teammates_list'] = ConciergeSpecialist.objects.filter(Q(org_unit_name=self.request.user.org_unit_name) & Q(active=True))
        context['responsible'] = responsible
        return context

    def get_queryset(self):
        responsible = ConciergeSpecialist.objects.get(id=self.kwargs['pk'])
        queryset = super(UserThreadsListView, self).get_queryset()
        return queryset.filter(tweet__responsible=responsible).order_by('id', '-tweet__created_at').distinct('id')

然后我使用{% for thread in threads_list %} 遍历模板tweetsview.html 中的线程。

我可以看到我的数据库中的数据,但是由于某种原因它没有被检索到模板中。只有第一次检索的旧数据才能正确显示在模板中。我该如何解决这个问题?

我的线程模型

class Thread(models.Model):

    name = models.CharField(max_length=50, null=True, blank=True)

    class Meta:
        ordering = ['id']

【问题讨论】:

  • 你能分享你的模型定义吗? Thread 属性 id 是唯一的吗?
  • 是的,它是独一无二的,它是 django 自动分配的。在上面添加了我的 Threads 模型
  • 是不是因为你分页了 20 而没有显示其余的结果?
  • 我认为这是订购的问题,但我不明白如何解决它。较新的项目确实出现在列表的末尾:-(
  • 使用 Django,您需要在向数据库添加新数据后发出新请求(刷新)以获取数据。除非您直接从服务器渲染。你在使用 django 模板吗?

标签: django python-3.x django-models django-rest-framework django-queryset


【解决方案1】:

订购方式:

class Meta:
    ordering = ['id']`

将按升序排列您的模型。听起来您希望它们首先列出最近创建的。如果是这种情况,请使用:

class Meta:
    ordering = ['-id']`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    相关资源
    最近更新 更多