Django model object with foreign key creation

DjangoDjango Models

Django Problem Overview


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?

Django Solutions


Solution 1 - Django

What you’re after is:

TestModel.objects.create(testkey_id=1)

Solution 2 - Django

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)

Solution 3 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondragoonView Question on Stackoverflow
Solution 1 - DjangosneeuView Answer on Stackoverflow
Solution 2 - DjangoZohab AliView Answer on Stackoverflow
Solution 3 - DjangoDhruvil AminView Answer on Stackoverflow