justme8910
justme8910

Reputation: 11

Django post_save: database not yet updated?

I'm writing a Django application for ordering stuff. All orders have a certain 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. I'm using a post_save signal to check if my db already has a common order for a user for a certain delivery. 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? How can I prevent this behavior? I'm using a sqlite3 db.

Upvotes: 0

Views: 207

Answers (1)

justme8910
justme8910

Reputation: 11

Ok, so after trying many different things, I finally found a solution (which is actually quite simple): just add Order.objects.update() before calling get_or_create()

Upvotes: 1

Related Questions