Rubén Jiménez
Rubén Jiménez

Reputation: 1845

How to make Django queries retrieve updated information from database?

For 2 days i have been stucked at transaction problem in my Django project. I'm developing a messenger system and when i send a message to some user, the sent message appears correctly in outbox div (with jQuery/Ajax, not refresh page). Well, If i send another message, the new message which appears in outbox now is the same as previous sent.

All messages i send are like the first. In database table the messages are well saved, so i guess problem comes from query.

The query is next:

@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/')

let's pay attention to line "print sent.recipient.username". This line always print the first message recipient name.

I have been reading some threads around stackoverflow talking about this problem, but handling manually the transactions i haven't got any success. Even making "Message.objects.update()" before the query it doesn't work.

Any suggestion? It's very annoying to not understand how does it happening.

If you need more information like model code or whatever, tell it to me.

Thanks!

Upvotes: 0

Views: 127

Answers (1)

Greg
Greg

Reputation: 10342

You query is ordering the results by "send_at", which presumably gives you the first message sent. If you want the last, you'll need to order on "-send_at", eg.

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

Upvotes: 2

Related Questions