开发者

django: how many queries

开发者 https://www.devze.com 2023-02-10 10:17 出处:网络
a noob question here. After reading the docs, I foun开发者_开发技巧d that saving a model with a foreign key reference requires saving a model instance of the object being referenced.

a noob question here.

After reading the docs, I foun开发者_开发技巧d that saving a model with a foreign key reference requires saving a model instance of the object being referenced.

a = ModelA.objects.get(pk=1)
b = ModelB(foreignk = a,.....)
b.save()

In this case, how many queries are actually executed? If I have the pk of the referenced model, is this the correct method to go ahead?


Every ForeignKey field also results in a hidden field having the same name but with _id appended. Assigning the foreign PK to that field is enough.

b = ModelB(...)
b.foreignk_id = 1
b.save()


If you use your solution, you have 2 queries: one for evaluating the queryset for ModelA when you pass it as an argument to ModelB, the second when you call save().

Using Ignacios solution you have just one when saving.

0

精彩评论

暂无评论...
验证码 换一张
取 消