Home > database >  paginate related queryset in django
paginate related queryset in django

Time:12-08

I have two models named Card and Comment, both are related with a foreign key

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)

I want to access card along with limited (comment size say 5) comments with select_related or prefetch_related query

I have a load more button for comments, so when ever i press load more i want 5 more comments to be fetched

someone pls answer, thnks:)

CodePudding user response:

To paginate a related queryset in Django REST, you can use the LimitOffsetPagination class from the rest_framework.pagination module. This class allows you to paginate a queryset and generate the appropriate page links for use in a REST API response.

from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response

def my_view(request):
    # Get the related queryset
    related_objects = MyModel.objects.filter(my_field=my_value).select_related('related_model')

    # Create a paginator for the queryset
    paginator = LimitOffsetPagination()
    paginated_queryset = paginator.paginate_queryset(related_objects, request)

    # Serialize the paginated queryset
    serializer = MyModelSerializer(paginated_queryset, many=True)
    serialized_data = serializer.data

    # Return the paginated objects in the response
    return Response(serialized_data)

the related queryset using the select_related method to optimize the query. It then creates a LimitOffsetPagination object and uses the paginate_queryset method to paginate the queryset.

Next, it serializes the paginated queryset using the MyModelSerializer serializer and returns the serialized data in the response. The pagination information, such as the page size and page links, will be included in the response headers.

You can also create a custom pagination ref to Doc

CodePudding user response:

To paginate a queryset in Django, you can use the Paginator class:

This will paginate the queryset, allowing you to access only the items on the specified page.

To paginate a queryset that includes related objects, you can use the select_related method to prefetch the related objects.

Here's an example:

# Assume that your queryset includes related objects, and that you want to prefetch them
my_queryset = Card.objects.select_related('commets').all().values("image", "email", "mobile", "name", "comments__image", "comments__comment", "comments_valid")

# 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

  • Related