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?
First of all, anything is possible. Models can have multiple foreign keys.
Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .
The __str__ method just tells Django what to print when it needs to print out an instance of the any model.
What you’re after is:
TestModel.objects.create(testkey_id=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With