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:)
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 = 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.