88

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?

dragoon
  • 5,601
  • 5
  • 37
  • 55

3 Answers3

137

What you’re after is:

TestModel.objects.create(testkey_id=1)
Daniel Benedykt
  • 6,496
  • 12
  • 51
  • 73
sneeu
  • 2,602
  • 3
  • 24
  • 27
  • 1
    Yes, you're right, but for some reason it does not work with get_or_create :( – dragoon Nov 16 '10 at 15:01
  • 2
    @dragon: I believe TestModel2.objects.get(testkey_id=1) doesn't work either. – Tomasz Zieliński Nov 16 '10 at 20:30
  • 16
    @Tomasz no, that won’t work, but `TestModel2.objects.get(testkey__id=1)`, and `TestModel2.objects.get_or_create(testkey__id=1)` will work (note the double underscore). It’s very possible though that these will raise `MultipleObjectsReturned`. – sneeu Nov 16 '10 at 22:19
  • 1
    What if the foreign key has a to_field value that is different than "id"? – kloddant Oct 12 '20 at 16:52
  • 2
    @kloddant as far as I can tell, the field is always called `«foreign-key-name»_id` regardless of `to_field` or the primary-key of the related model. – sneeu Oct 15 '20 at 10:56
  • @sneeu, Thanks! Yes, I have confirmed this just yesterday by testing it out. It is indeed «foreign-key-name»_id, regardless of the to_field. – kloddant Oct 15 '20 at 13:32
18

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)

Zohab Ali
  • 8,426
  • 4
  • 55
  • 63
12

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

4b0
  • 21,981
  • 30
  • 95
  • 142
Dhruvil Amin
  • 761
  • 1
  • 7
  • 18