【问题标题】:How to make Django queries retrieve updated information from database?如何让 Django 查询从数据库中检索更新的信息?
【发布时间】:2012-05-13 12:47:12
【问题描述】:

两天来,我一直被 Django 项目中的事务问题困扰。我正在开发一个信使系统,当我向某个用户发送消息时,发送的消息正确显示在发件箱 div 中(使用 jQuery/Ajax,而不是刷新页面)。好吧,如果我发送另一条消息,现在发件箱中出现的新消息与之前发送的相同。

我发送的所有消息都和第一条一样。在数据库表中,消息保存得很好,所以我猜问题来自查询。

查询是下一个:

@login_required(login_url='/')
def getmessage(request, mode=None):
if request.is_ajax():
    if request.method == "GET":
        # Retrieve last message sent by user
        Message.objects.update()
        q = Message.objects.filter(sender=request.user).order_by('send_at')[:1]

        response = {}
        for sent in q:
            sent_message = {}
            sent_message['recipient'] = sent.recipient.username
            print sent.recipient.username
            sent_message['body'] = sent.body
            response.update({'sent': sent_message})

        # Make json object
        json = simplejson.dumps(response)

        # Send answer to client side
        return HttpResponse(json, mimetype='application/json')
    else:
        # No POST request, redirecting
        return HttpResponseRedirect('/messenger/')
else:
    # No AJAX request, redirecting
    return HttpResponseRedirect('/messenger/')

让我们注意“print sent.recipient.username”行。此行总是打印第一个消息收件人姓名。

我一直在阅读有关 stackoverflow 的一些线程,讨论这个问题,但手动处理事务我没有取得任何成功。即使在查询之前制作“Message.objects.update()”也不起作用。

有什么建议吗?不明白它是如何发生的,这很烦人。

如果您需要更多信息,例如型号代码或其他信息,请告诉我。

谢谢!

【问题讨论】:

    标签: mysql django caching transactions


    【解决方案1】:

    您的查询是按“send_at”对结果进行排序,这可能会给您发送的第一条消息。如果你想要最后一个,你需要在“-send_at”上订购,例如。

    q = Message.objects.filter(sender=request.user).order_by('-send_at')[:1]
    

    【讨论】:

    • 天哪……现在它起作用了……花了 2 天时间试图解决这个愚蠢的问题。我很抱歉,因为为此创建了一个线程。非常感谢伙计。
    • 哎呀。不要感觉太糟糕......这种事情在某些时候会打击每个人!
    猜你喜欢
    • 2015-06-02
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    相关资源
    最近更新 更多