我正在尝试创建像 facebook 一样的通知。一切正常,但我有重复。例如,action = like, url = post/1 我想获取所有 status = 1 的通知 - 未读并消除 action 和 url 相同的重复项。你可以在下面找到代码我有这样的错误:
错误:“列表索引超出范围”在
if n_dup[i]['url'] == n_dup[j]['url'] and n_dup[i]['action'] == n_dup[j]
def recieve_notification(request):
t = loader.get_template('notifications.html')
nots = Notification.objects.filter(recipent=request.user, status=1, pub_date__gte=datetime.datetime.now()-datetime.timedelta(days=3))
n_dup = [] #list of notifications with duplicates
for n in nots:
n_dup.append({'id':n.id, 'url':n.url, 'action':n.action})
i = len(n_dup)-1
j = len(n_dup)-1
while j>=0:
while i>=0:
if n_dup[i]['url'] == n_dup[j]['url'] and n_dup[i]['action'] == n_dup[j]['action'] and i is not j:
del n_dup[i]
i-=1
j-=1
out_n = []
for n in n_dup:
n_id = n['id']
out_n.append(Notification.objects.get(id=n_id))
c = RequestContext(request, {'notifications':out_n, 'notifications_count':len(out_n)})
return HttpResponse(t.render(c))`
也许您知道编写所有这些东西的更好方法?