如何在Django中同步请求的数据

huangapple go评论69阅读模式
英文:

How to synchronize requested data in Django

问题

Request test18 to execute first, request test17 to execute later. However, request test18 will complete the data update first, and request test17 to complete the data update later

This will cause the result of request test17 to overwrite the result of test18. How can I ensure that the results of test17 do not overwrite the results of test18?

Here is my django code:

def test17(request):
  obj = Book.objects.filter(id=1)[0]
  obj.book_name = 'history'
  obj.save()
  return HttpResponse("Success!")

def test18(request):
  obj = Book.objects.filter(id=1)[0]
  obj.num = 2
  # Ensure that test17 is processed first
  time.sleep(2)
  obj.save()
  return HttpResponse("Success!")

Source SQL data: id:1 book_name match num:0

SQL data after request id:1 book_name match num:2

I hope the data from test18 will not overwrite the data from test17. During the data processing period of test18, test17 completed the data update. How should I handle this situation?

英文:

Assuming I have requested test18 and requested test17

Request test18 to execute first, request test17 to execute later. However, request test18 will complete the data update first, and request test17 to complete the data update later

This will cause the result of request test17 to overwrite the result of test18 How can I ensure that the results of test17 do not overwrite the results of test 18

Here is my django code

def test17(request):
  obj = Book.objects.filter(id=1)[0]
  obj.book_name = 'history'
  obj.save()
  return HttpResponse("Success!")


def test18(request):
  obj = Book.objects.filter(id=1)[0]
  obj.num = 2
  # Ensure that test17 is processed first
  time.sleep(2)
  obj.save()
  return HttpResponse("Success!")

Source sql data: id:1 book_name match num:0

SQL data after request id:1 book_name match num:2

I hope the data from test18 will not overwrite the data from test17. During the data processing period of test18, test17 completed the data update. How should I handle this situation

答案1

得分: 0

你可以在test17中设置一个标志,并将其保存在你的book对象中,这样你就可以在test18中检查这个标志,确保test17被完全处理。

英文:

You can set a flag in test17 and save it in your book obj so you can check the flag in test18 and ensure that test17 is processed first completely.

huangapple
  • 本文由 发表于 2023年5月18日 10:16:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定