Django .save() Reverts
I have an InteferField set in models called the status. I have a method that is two switch the value of two rows statuses.
Row one -> status = 1
Row two -> status = 2
Now, I figure, if I switch row one's status to some unattainable reach (99) I could use that as the middle man to switch row two and then switch row one.
Get status = 1 -> Row one
Get status = 2 -> Row two
Set Row one -> status = 99
Save Row one
Set Row two -> status = 1
Save Row two
Get status = 99 -> Row one
Set Row one -> status = 2
Save Row one
The strange thing is, the data reverts. If I just change the status of Row one to 99, it will change to 99 and then a moment later, back to its original value. We're not sure why this is happening, but it turns out nothing is come from this at all.
original = 1
swap = 2
originalCase = Case.objects.get(queu开发者_开发百科e_num = original)
#swapCase = Case.objects.get(queue_num = swap)
originalCase.queue_num = 99
originalCase.save()
#swapCase.queue_num = original
#swapCase.save()
#originalCase = Case.objects.get(queue_num = 99)
#originalCase.queue_num = swap
#originalCase.save()
return HttpResponse(Case.objects.filter(queue_num__gt=0).order_by('queue_num'))
Is it because we're querying to fast and it's not updating in time for the next update? Or is there a flaw in my logic?
Hmmm... Shouldn't the following:
originalCase = Case.objects.get(queue_num = swap)
Be this:
originalCase = Case.objects.get(queue_num = 99)
If you copy and pasted that code as is, that's your problem. You're essentially fetching the one you just changed and changing it back.
UPDATE:
Simplifying your code may help ferret out the problem, as well. You don't technically need a swap placeholder. Since the query hits the database only once when initially fetching all the objects, you could do something like the following:
cases = Case.objects.all()
for case in cases:
if case.queue_num == original:
case.queue_num = swap
elif case.queue_num == swap:
case.queue_num = original
case.save()
Or if you want to keep the same idea, you could even do the following (which might actually be simpler):
Case.objects.filter(queue_num=original).update(queue_num=99)
Case.objects.filter(queue_num=swap).update(queue_num=original)
Case.objects.filter(queue_num=99).update(queue_num=swap)
line 2,3,4 from the bottom have no effect:
originalCase = Case.objects.get(queue_num = swap)
originalCase.queue_num = swap
originalCase.save()
精彩评论