我希望在首次加载时从我的Articles
模型中获取10篇文章,然后在用户通过AJAX
向下滚动时再获取10篇文章。我将前10个的id存储在一个数组中,然后将后续的id附加到它。这是为了启用不在该列表中的文章,但是我得到空数组,当我一次又一次滚动到底部时,仍会获取前10篇文章。
首次加载:
import json
my_interest = user_object.interet #this returns [3,4,55,24,57]
articles = Articles.objects.all()[:10]
fetched = [x.id for x in articles]
request.session['fetched'] = json.dumps(fetched)
另外10个来自AJAX:
import operator
fetched = json.loads(request.session['fetched'])
my_interest = user_object.interet #this returns [3,4,55,24,57]
query = reduce(operator.and_,[Q(cat_id__in = my_interest ), ~Q(id__in = fetched )])
articles = Articles.objects.filter(query)[:10]
request.session['fetched'] = json.dumps( fetched + [x.id for x in articles])
context = {'articles': articles, 'fetched': request.session['fetched']}
return render_to_response('mysite/loadmore.html', context)
但是当我滚动到页面底部时,我仍然获得与首次重复获取的相同的10,如果我在模板上<p> Fetched: {{fetched}} </p>
,我只看到 Fetched:
答案 0 :(得分:0)
Q(id__in = fetched )
看起来您要求使用相同ID的文章,您已经提取并保存到会话?
答案 1 :(得分:0)
我不确定这是否是你的问题,但你的查询中不需要reduce或Q.写起来更简单,更清晰:
articles = Articles.objects.filter(cat_id__in=my_interest).exclude(id__in=fetched )
在将ID保存到会话时,向JSON转储/加载也没有意义。会话已经处理序列化。只是做:
fetched = request.session['fetched']
...
request.session['fetched'].extend([x.id for x in articles])