[Answer]-Proper Way to Fetch Latest Addition to Django Model

1๐Ÿ‘

โœ…

A better way to do this is to record in the session an identifier from the last record to be shown, and then query for those records that are after that. You could use the pk for that, but it would probably be safer to explicitly set a created_at datetimefield (using auto_now_add). Now you can do:

last_fetched = request.session['last_fetched']
new_posts = list(Post.objects.filter(created_at__gt=last_fetched)[:20])
request.session['last_fetched'] = new_posts[19].created_at

Leave a comment