Django multiple queryset combine into a pagination

2019-05-15 22:12发布

I have combine 2 queryset from different models into a list and used pagination to display as a single list.

The problem is the objects from the list are displayed by the pagination according to the models they were created from.

enter image description here

How could I fix the list so when a new object is created from the models. It will be displayed after the recently created object even though the recent object created was from a different models.

Example would be . I have a combine queryset of user's whiteboard and user's comment. If a new whiteboard 's object was created recently and I would create another comment . The comment would be displayed by the pagination after the whiteboard 's object instead of been displayed with all the other comments further down the paginated because it was in a different models

enter image description here

I hope you can get the idea of what i'm trying to achieve :)

Parts of my module

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)

views.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})

archive.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>

1条回答
Luminary・发光体
2楼-- · 2019-05-15 22:45

You just need to sort your list of combined querysets by the created attribute they both share:

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

查看更多
登录 后发表回答