开发者

django: how many queries

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜