paginate相关的查询集



我有两个名为Card和Comment的模型,它们都与一个外键相关

class Card(models.Model):
image = models.CharField(max_length=100, default="")
email = models.EmailField(unique=True, max_length=30, null = False, blank=False, default="")
mobile = models.CharField(unique=True, max_length=12, null = False, blank=False, default="")
uploaded_time = models.DateTimeField(auto_now_add=True)
name = models.CharField(unique=True, max_length=30, null = False, blank=False, default="")
active = models.BooleanField(default=True)
def __str__(self):
return self.name
class Comment(models.Model):
image = models.ForeignKey(Card, on_delete=models.CASCADE, related_name="comments")
comment = models.CharField(max_length=100, blank=False, null=False)
valid = models.BooleanField(default=False)

我想访问卡以及有限的(评论大小说5)评论与select_related或prefetch_related查询

我有一个load more按钮用于评论,所以当我按load more时,我想要获取5个以上的评论

谁来回答一下,谢谢:)

要在Django中分页一个查询集,你可以使用Paginator类:

这将对查询集进行分页,允许您仅访问指定页面上的项。

要对包含相关对象的查询集进行分页,可以使用select_related方法预取相关对象。

下面是一个例子:

# Assume that your queryset includes related objects, and that you want to prefetch them
my_queryset = Comment.objects.filter(image__id=your_id).values("comment")
# Create the paginator object as described above
paginator = Paginator(my_queryset, 5)
# Get the page number from the query string
page_number = request.GET.get('page')
# Get the page object for the specified page number
page_obj = paginator.get_page(page_number)
# Use the page object to access the items on the specified page
page_items = page_obj.object_list

相关内容

  • 没有找到相关文章

最新更新