Django model object with foreign key creation

Hi Suppose I have a simple model class like this:

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

When I am creating a TestModel object I have to pass to it an instance of the TestModel2 object to create it:

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

This results in 2 queries to database I suppose, and I have a list of Foreign key IDs that I need to create objects with.

Is it possible to create objects with foreign keys without initially retrieving the foreign key objects?


Solution 1:

What you’re after is:

TestModel.objects.create(testkey_id=1)

Solution 2:

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)