[英]Django post_save: database not yet updated?
I'm writing a Django application for ordering stuff. 我正在编写用于订购商品的Django应用程序。 All orders have a certain type Type.
所有订单都有特定的类型Type。 If Type.is_common == true, it needs to be included in a delivery no matter if a user orders this type or not.
如果Type.is_common == true,则无论用户是否订购此类型,都必须将其包含在交付中。 I'm using a post_save signal to check if my db already has a common order for a user for a certain delivery.
我正在使用post_save信号来检查我的数据库是否已经为某个交货用户提供了通用订单。 Here is the code:
这是代码:
@receiver(post_save, sender=Order)
def create_common_order(sender, instance=None, created=False, **kwargs):
""" This signal handler creates common orders (if delivery type
definition contains any common types) for every first order of a
user for a certain delivery. """
# Don't handle this if the order is not for a delivery
if not created or not instance or not instance.delivery:
return
# Don't handle Order with common types
if instance.type.is_common:
return
# Loop through all types in type definition of delivery
for t in Type.objects.all():
# Look for a 'is_common' type
if type.is_common:
# Get or create an order with the respective values
Order.objects.get_or_create(
delivery=instance.delivery,
user=instance.user,
type=type,
defaults={'count':1}
)
My problem is the following: From time to time it happens that two common orders are created (if two new orders are created at almost the same time). 我的问题如下:有时会创建两个普通订单(如果几乎同时创建了两个新订单)。 But why?
但为什么? Is the db not yet updated in post_save?
db是否尚未在post_save中更新? How can I prevent this behavior?
如何防止这种行为? I'm using a sqlite3 db.
我正在使用sqlite3数据库。
好的,所以在尝试了许多不同的事情之后,我终于找到了一个解决方案(实际上很简单):只需在调用get_or_create()之前添加Order.objects.update()即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.