簡體   English   中英

Django視圖中的無限循環

[英]Infinite loop in django view

我一直在努力嘗試弄清楚為什么我不返回PrivateMessages列表。 有時,另一雙眼睛可以立即看到它,因此我在此發布,希望有人能發現錯誤。

此功能可獲取20條或更少的私人消息,並刪除同一用戶的重復消息,也就是說,在返回的pm中,每個用戶只有1條消息。

它還排除了“沉默”列表中的用戶。 這些工作正常,所以我認為與沉默位無關。

在調用remove_duplicate_users之后,我得到了最后一個對象的ID,以便在下一個查詢中使用它。

我沖洗並重復直到列表中有20個對象准備返回或查詢不返回任何內容。

def get_private_messages(request):
    ss = Silenced.objects.filter(user=request.user)
    last_pm_id = None
    n = 20
    bl = []
    while True:
        if last_pm_id:
            pmr = PrivateMessage.objects.filter(user=request.user,hidden=False,id__lt=last_pm_id).exclude(sender__in=[s.brat for s in ss]).order_by('-id')[:n]
        else:   
            pmr = PrivateMessage.objects.filter(user=request.user,hidden=False).exclude(sender__in=[s.brat for s in ss]).order_by('-id')[:n]
        l = list(pmr)
        bl = bl + l
        bl = remove_duplicate_senders(bl)
        n = 20 - len(bl)
        last_pm_id = bl[-1].id
        if len(bl) >= 20 or not pmr:
            break

    return HttpResponse(bl)

此功能可刪除重復的用戶消息。 對於名為pin或note的用戶,如果pm.info1與僅前10個pm的welcome匹配,它將成為一個例外。

def remove_duplicate_senders(pmr):
    l = []
    a = False
    for p in pmr:
        a = True
        if p.sender.username in ['pin','note'] or p.info1=='welcome':
            l.append(p)
            continue
        for px in l:
            if p.sender.username == px.sender.username:
                a = False
                break
        if a:
            l.append(p)
    return l

與我測試的用戶的時間超過60 pm,但是當我嘗試檢索前20 pm時,卻出現了無限循環。 它可以與其他用戶一起使用,但是第一個用戶訂購pm的方式導致錯誤。

對此表示感謝,謝謝。

我認為您的休息條件無效:

if len(bl) >= 20 or not pmr:
    # Stop if I have more than 20 messages? Shouldn't I continue filtering?
    break

應該:

if n >= 0:
    # Stop only if I have 20 or less [n = 20 - len(bl)], continue otherwise
    break

我可能誤解了一些東西,但是while循環的最后一部分是帶有副作用的。 並且請考慮重寫代碼以使其更清晰。

事實證明,同一用戶連續出現了太多的pm,因此當它嘗試獲取n條私人消息時,它從未達到20。我添加了一個函數來創建一個包含所有用戶的列表。 bl並將它們排除在查詢中。 感謝您的答復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM