问题很简单。我有一个func lazy_load_posts(),它通过AJAX请求将我所有的模型注释附加到所有相同的文章上,但是我只需要将相关注释附加到一篇文章上。我已经尝试过filter方法和prefetch_related,但是没有用。我还收到控制台POST http://localhost:8000/lazy_load_posts/ 500错误(内部服务器错误)
我的view.py
PhotoDetailView(DetailView)类:
queryset = Photo.objects.select_related('user').prefetch_related('comments', 'comments__user', 'likes')
context_object_name = 'photo'
template_name = 'photo_detail.html'
def get_success_url(self):
return reverse('photo_detail', kwargs={'pk': self.object.pk})
def get_context_data(self, **kwargs):
context = super(PhotoDetailView, self).get_context_data(**kwargs)
comments = self.object.comments.all()[:5]
context['comments'] = comments
context['form'] = AddCommentForm(initial={'post': self.object.pk})
context['is_liked_by_user'] = self.request.user in self.object.likes.all()
return context
def lazy_load_posts(请求):
page = request.POST.get('page')
comments = Comment.objects.all()
results_per_page = 5
paginator = Paginator(comments, results_per_page)
try:
comments = paginator.page(page)
except PageNotAnInteger:
comments = paginator.page(2)
except EmptyPage:
comments = paginator.page(paginator.num_pages)
posts_html = loader.render_to_string(
'comments.html',
{'comments': comments}
)
output_data = {
'posts_html': posts_html,
'has_next': comments.has_next(),
}
return JsonResponse(output_data)
and my script.js
$('#lazyLoadLink').on('click', function() {
var link = $(this);
var page = link.data('page');
$.ajax({
type: 'post',
url: '/lazy_load_posts/',
data: {
'page': page,
'csrfmiddlewaretoken': window.CSRF_TOKEN
},
success: function(data) {
console.log(data)
if (data.has_next) {
link.data('page', page+1);
} else {
link.hide();
}
$('#posts').append(data.posts_html);
},
error: function(xhr, status, error) {
}
});
});