Reputation: 4518
I have a Post object with comments and I am trying to send ajax requests in a while loop to check if there have been new comments created, and if there were, add them to the DOM.
How can you achieve that in django?
Here are my models:
class Post(models.Model):
name = models.CharField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
class PostComment(models.Model):
comment = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post', related_query_name='post')
date_added = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
I have tried to look into channels and web sockets but all the tutorials that I have found use old versions of django and python. So I decided to simply achieve the same with ajax requests in a while loop.
I am open to any suggestions about how to achieve my outcome!
Upvotes: 1
Views: 154
Reputation: 2627
You can use your date_added which is DateTimeField. On your requests, you can pass your last response of request's datetime and you can filter on date_added for has a bigger value your last request datetime. Please be carefull abouth date formats.
last_request_datetime = request.POST.get('last_request_datetime')
new_posts = Post.objects.filter(date_added__gt=last_request_datetime)
Upvotes: 1
Reputation: 881
A simple idea is querying your backend on post/comment pk (auto incremental default Django field), where the pk is greater then the maximum already queried.
Given a known max_pk
:
Post.objects.filter(pk__gt=max_pk)
Upvotes: 1