Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按其他字段的值保存django模型中的外键_Django_Python 3.x_Django Models - Fatal编程技术网

按其他字段的值保存django模型中的外键

按其他字段的值保存django模型中的外键,django,python-3.x,django-models,Django,Python 3.x,Django Models,我正在处理从API导入的苹果和桶。应使用模型将其写入Django数据库 restapi保存的Bucket的ID不是内部的,而是保存为本地Bucket模型中的external\u ID 本地Apple型号有一个字段bucket,这是一个型号:ForeignKey(bucket)字段 在检索和存储数据时,我无法找到如何连接这两者。有没有一种方法可以简单地让Django查询bucket表上的外部_id,然后使用结果行连接外键 a = Apple( 'name' = apple.name

我正在处理从API导入的苹果和桶。应使用模型将其写入Django数据库

restapi保存的Bucket的ID不是内部的,而是保存为本地Bucket模型中的
external\u ID

本地Apple型号有一个字段
bucket
,这是一个
型号:ForeignKey(bucket)
字段

在检索和存储数据时,我无法找到如何连接这两者。有没有一种方法可以简单地让Django查询bucket表上的外部_id,然后使用结果行连接外键

a = Apple(
    'name' = apple.name
    'count' =  apple.count
    'bucket' = ???
)

a.save()

您可以简单地执行以下操作:

a = Apple(name=..., count=...)  # note there are no quotes around the field names here
a.bucket = Bucket.objects.get(external_id=external_id_from_your_rest_api)
a.save()

您可以简单地执行以下操作:

a = Apple(name=..., count=...)  # note there are no quotes around the field names here
a.bucket = Bucket.objects.get(external_id=external_id_from_your_rest_api)
a.save()

bucket.external\u id
字段中添加
unique=True
也是个好主意。这将添加一个索引,该索引将检查唯一性并加快对该字段的查询。在
bucket.external_id
字段中添加
unique=True
也是一个好主意。这将添加一个索引,该索引将检查唯一性并加快此字段的查询速度。谢谢,我不知道单引号是如何输入的,但我的代码中没有单引号-谢谢您的帮助!谢谢,我不知道单引号是怎么出现的,但是我的代码中没有单引号-谢谢你的帮助!