gpt4 book ai didi

Django 多个查询集组合成分页

转载 作者:行者123 更新时间:2023-12-02 06:47:00 24 4
gpt4 key购买 nike

我将来自不同模型的 2 个查询集合并到一个列表中,并使用分页显示为单个列表。

问题是列表中的对象根据创建它们的模型通过分页显示。

enter image description here

当从模型创建新对象时,我该如何修复列表。即使最近创建的对象来自不同的模型,它也会显示在最近创建的对象之后。

示例是 .我有一个用户白板和用户评论的组合查询集。如果最近创建了新的白​​板对象,我将创建另一个注释。注释将通过分页显示在白板对象之后,而不是与分页下方的所有其他注释一起显示,因为它位于不同的模型中

enter image description here

我希望您能了解我想要实现的目标:)

我的模块的一部分

class WhiteBoard(models.Model):

user = models.ForeignKey(User)
name = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
def __unicode__(self):
return self.name


class Comment(models.Model):
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
body = models.TextField()
picture = models.ForeignKey(Picture)

View .py

@login_required
def archive(request):
user = User.objects.get(username=request.user)
person = Person.objects.get(user=user)
users = User.objects.filter(pk__in=person.following.all().values_list('user__pk',flat=True))
picture = whiteboard .objects.filter(user__in=users).order_by("-created")
comment = Comment.objects.filter(user__in=users).order_by("-created")
posts= list(chain(picture,comment))
paginator = Paginator(posts, 5)

try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1

try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request,'archive.html',{'picture':picture,'comment':comment,'posts':posts})

存档.html

{% for post in posts.object_list %}

{{post.name }}
<br>
{{post.body}}
{% endfor %}

<!-- Next/Prev page links -->
{% if posts.object_list and posts.paginator.num_pages > 1 %}
<div class="pagination" style="margin-top: 20px; margin-left: -20px; ">
<span class="step-links">
{% if posts.has_previous %}
<a href= "?page={{ posts.previous_page_number }}">newer entries &lt;&lt; </a>
{% endif %}

<span class="current">
&nbsp;Page {{ posts.number }} of {{ posts.paginator.num_pages }}
</span>

{% if posts.has_next %}
<a href="?page={{ posts.next_page_number }}"> &gt;&gt; older entries</a>
{% endif %}
</span>
</div>
{% endif %}

</div>

最佳答案

您只需要sort您的组合查询集列表(按它们共享的 created 属性列出):

from itertools import chain
...
posts = list(
sorted(
chain(picture,comment),
key=lambda objects: objects.created,
reverse=True # Optional
))
paginator = Paginator(posts, 5)
...

Here's a similar question on the topic

关于Django 多个查询集组合成分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com