Django散装用外键创建到另一个字段

发布于 2025-01-21 19:21:21 字数 950 浏览 1 评论 0原文

当它们具有外键时,我想创建对象,而其外键不是ID字段。 (当to_field值为id时,您可以在创建中使用model_id引用

它:

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

和一个名为帐户的模型:

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

我尝试使用以下方式创建对象:

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
        )

我会收到以下错误:

typeError:credit()有一个意外的关键字参数'account__account_id'

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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁把谁当真 2025-01-28 19:21:21

这是不可能的,因为您正在触摸两个表:信用帐户。因此,无论如何,您至少需要两个插入

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文