Monday, September 11, 2017

Re: Retrieving objects created in trasaction

Thanks to everyone and sorry for the delay, I've missed your responses.

I've tried to use transaction.on_commit, it didn't work for me. For some strange reason Django thought the code wasn't running in a transaction.

I'm using Django 1.10 and PostgreSQL 9.6. Bar uses standard manager and yes, I can fetch objects after transaction has finished.

I ended up with local storage for newly created objects. So I query database for existing objects I've added to relation and if original pk_set is bigger I also query that local storage. That fixed the problem for me, but it's not exactly a good solution.

On 24 Aug 2017, at 18:47, Daniel Hepper <daniel.hepper@gmail.com> wrote:

I cannot reproduce this behavior with Django 1.11 and PostgreSQL 9.6. What database are you using?

Does your Bar model maybe use non-standard Manager? Can you actually fetch to objects after the transaction has finished?


On Wednesday, August 16, 2017 at 8:29:09 PM UTC+2, Александр Христюхин 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?


--
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/e9c89d82-e92b-4de0-bf6a-52f4e505d6fc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment