Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
dragoon Avatar asked Nov 16 '10 14:11

dragoon


People also ask

Can a model have two foreign keys in Django?

First of all, anything is possible. Models can have multiple foreign keys.

Does Django create index for ForeignKey?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.


1 Answers

What you’re after is:

TestModel.objects.create(testkey_id=1) 
like image 82
sneeu Avatar answered Sep 19 '22 14:09

sneeu