Django散装用外键创建到另一个字段
当它们具有外键时,我想创建对象,而其外键不是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是不可能的,因为您正在触摸两个表:
信用
和帐户
。因此,无论如何,您至少需要两个插入
。That's not possible because you are touching two tables:
Credit
andAccount
. So you need at least twoINSERT
s anyways.