'Django bulk create with foreign key to another field

I want to bulk create objects, when they have a foreign key and their foreign key is not id field. (When to_field value is id you can reference it with model_id in creation but I haven't found a way to do id with another field.)

I have a model named Credit:

class Credit(models.Model):
    account = models.ForeignKey('finance.Account', to_field='account_id', on_delete=models.PROTECT)
    amount = models.PositiveBigIntegerField()

and a model named Account:

class Account(models.Model):
    account_id = models.UUIDField(
        verbose_name=_("account id"),
        db_index=True,
        null=True,
        unique=True,
    )

and I tried to create objects with:

accounts = [] # list of uuids

 credits = [
            Credit(
                account__account_id=a, 
                amount=amount, 
            ) for a in accounts]
        created_objects = Credit.objects.bulk_create(
            credits, ignore_conflicts=True
        )

and I get the following error:

TypeError: Credit() got an unexpected keyword argument 'account__account_id'



Solution 1:[1]

That's not possible because you are touching two tables: Credit and Account. So you need at least two INSERTs anyways.

accounts_uuids = []
amount = 0

accounts = [Account(account_id=uuid) for uuid in accounts_uuids]
Account.objects.bulk_create(objs=accounts)

credits = [Credit(account=account, amount=amount) for account in accounts]
Credit.objects.bulk_create(objs=credits, ignore_conflicts=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Murilo Sitonio