创建外键的 Django 模型对象

嗨 假设我有这样一个简单的模型类:

class TestModel(models.Model):
testkey = models.ForeignKey(TestModel2)
...

当我创建一个 TestModel 对象时,我必须传递给它一个 TestModel2对象的实例来创建它:

testkey =TestModel2.objects.get(id=...)
TestModel.objects.create(testkey=testkey)

这会导致对数据库的两个查询,我有一个需要用来创建对象的外键 ID 列表。

是否有可能创建具有外键的对象而不首先检索外键对象?

76545 次浏览

What you’re after is:

TestModel.objects.create(testkey_id=1)

In get_or_create it will fail in get. So to make get_or_create work below is the solution:

TestModel.objects.get_or_create(testkey=TestModel2(id=1))

Reference: https://code.djangoproject.com/ticket/13915

In my case TestModel.objects.create(testkey__id=1) didn't work for me so I had to put one underscore instead of two, for example

TestModel.objects.create(testkey_id=1)