Wednesday, August 23, 2017

Re: Retrieving objects created in trasaction



On Aug 16, 2017 11:27 AM, "roboslone -" <roboslone@gmail.com> wrote:
Hi,

I have some function (fetcher) that runs in transaction (it has to) and it creates a bunch if new objects that are written to database after transaction is commited. Those objects are added to a many-to-many relation. And on that relation change a signal is fired and handled by my signal handler, that collects objects from relation and writes them into some cache.

The problem is that during signal handling newly created objects do have PKs, but are not in database yet. So signal_handler in code below always gets empty queryset.


def fetcher():
    with transaction.atomic():
        foo = Foo.objects.create(...)
        foo.bars.add(
            Bar.objects.create(...),
            Bar.objects.create(...),
            Bar.objects.create(...),
            ...
        )

@receiver(m2m_changed, sender=Foo.bars.through)
def signal_handler(pk_set=None, **kwargs):
    # signal_handler is being called inside of a transaction block
    Bar.objects.filter(pk__in=pk_set)  # <-- returns empty QuerySet!


Is there a way to delay signal handling until transaction is committed or to get newly created objects by PKs?


Perhaps you can try nesting the transactions?


-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVTBFTQwHR01eEJqdqDfEiOu5nZZOtbGPrW-Lf2sUrmag%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment