Django post_save:数据库尚未更新?

时间:2017-11-29 20:16:56

标签: python django sqlite

我正在编写一个Django应用程序来订购东西。所有订单都有某种类型。如果Type.is_common == true,则无论用户是否订购此类型,都需要将其包含在交付中。我使用post_save信号来检查我的数据库是否已经为某个交付的用户提供了一个共同的订单。这是代码:

@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}
               )

我的问题如下:有时会发生两个常见订单(如果几乎同时创建两个新订单)。但为什么? db_s尚未在post_save中更新吗?我该如何防止这种行为? 我使用的是sqlite3 db。

1 个答案:

答案 0 :(得分:0)

好的,所以在尝试了很多不同的东西后,我终于找到了一个解决方案(实际上非​​常简单):只需添加即可 在调用get_or_create()

之前调用Order.objects.update()