GrantU
GrantU

Reputation: 6555

bulk_create how to call function on each object

In reference to the following bulk_create query:

objs = [
        Message(
            recipient_number=e.mobile,
            content=content,
            sender=e.contact_owner,
            billee=user,
            sender_name=sender,
            gateway=gateway,
        )
        for e in query

    ]
    # Send messages to DB
    Message.objects.bulk_create(objs)

My issue:

I have to use bulk_create (for performance reasons). However I need to call instance.send(gateway) on every object that's created.

Using bulk create I don't seem to beable to do it because PK is not necessarily available for post_save signal meaning this won't work....

@receiver(post_save, sender=Message)
def my_post_save_handler(sender, instance, **kwargs):
    instance.send(instance.gateway)

post_save.connect(my_post_save_handler, sender=Message)

So I have tried a few other things like this....

objs = [
    Message(
       etc...
    ).send(gateway)
    for e in query

]

again this won't work.

This issue is driving me a little mad, it's very simple, so what options do I have with example?

I don't wont to use create, have to stay with bulk_create as I'm inserting millions of objects!

Thank you. :)

Upvotes: 0

Views: 708

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

You are trying to save the result of send, but send returns None. Instead you should call send in each object in turn, then send all the objects to bulk_create:

for obj in objs:
    obj.send(gateway)
Message.objects.bulk_create(objs)

Upvotes: 1

Related Questions