不必要的相关字段查找

时间:2014-03-05 11:41:35

标签: django django-models django-orm

我有一个django模型,看起来像这样:

class A(models.Model):
    b = models.ForeignKey(B)
    n = models.IntegerField()

我的django-shell配置为在触发后立即打印所有sql查询。 所以,写作

a = A.objects.get(id=10)

打印一个查询以从表A中检索对象。

我不明白的是,写print a.n会触发查询以检索相关的B元素。

有人可以解释为什么Django在我还没有访问它时需要检索元素B的原因吗? (我也不打算这样做。所以这对我来说是一个开销。)

修改

这是@Daniel要求的原始代码:

>> x=PlayedGamesModel.objects.get(pkey='i01E25D45526E14EA0A490D36@AdobeID16688802f8024509a8e431b644108a82')
[2014-03-05 12:46:15,174] (0.326) SELECT `appConnexions_playedgamesmodel`.`pkey`, `appConnexions_playedgamesmodel`.`user_id`, `appConnexions_playedgamesmodel`.`game_id`, `appConnexions_playedgamesmodel`.`playedFromBrowser`, `appConnexions_playedgamesmodel`.`playedFromConnexions`, `appConnexions_playedgamesmodel`.`deleted`, `appConnexions_playedgamesmodel`.`timestamp` FROM `appConnexions_playedgamesmodel` WHERE `appConnexions_playedgamesmodel`.`pkey` = 'i01E25D45526E14EA0A490D36@AdobeID16688802f8024509a8e431b644108a82' ; args=('i01E25D45526E14EA0A490D36@AdobeID16688802f8024509a8e431b644108a82',)
>> print x.playedFromConnexions
1
[2014-03-05 12:46:17,993] (0.319) SELECT `appConnexions_gamemodel`.`gameID`, `appConnexions_gamemodel`.`gameURL`, `appConnexions_gamemodel`.`title`, `appConnexions_gamemodel`.`longTitle`, `appConnexions_gamemodel`.`category`, `appConnexions_gamemodel`.`description`, `appConnexions_gamemodel`.`iconURL`, `appConnexions_gamemodel`.`screenshotURL`, `appConnexions_gamemodel`.`genre`, `appConnexions_gamemodel`.`minOS`, `appConnexions_gamemodel`.`price`, `appConnexions_gamemodel`.`isBlacklisted`, `appConnexions_gamemodel`.`swfURL`, `appConnexions_gamemodel`.`androidURL`, `appConnexions_gamemodel`.`windowsURL`, `appConnexions_gamemodel`.`iosURL`, `appConnexions_gamemodel`.`publisher_id`, `appConnexions_gamemodel`.`lastUpdated` FROM `appConnexions_gamemodel` WHERE `appConnexions_gamemodel`.`gameID` = '16688802f8024509a8e431b644108a82' ; args=(u'16688802f8024509a8e431b644108a82',)
[2014-03-05 12:46:18,597] (0.292) SELECT `appConnexions_usermodel`.`userID`, `appConnexions_usermodel`.`fID`, `appConnexions_usermodel`.`gID`, `appConnexions_usermodel`.`name`, `appConnexions_usermodel`.`avatarURL`, `appConnexions_usermodel`.`age`, `appConnexions_usermodel`.`country`, `appConnexions_usermodel`.`email`, `appConnexions_usermodel`.`settingsBitset`, `appConnexions_usermodel`.`allowLogin`, `appConnexions_usermodel`.`allowAutomaticAdd`, `appConnexions_usermodel`.`allowActivityShare`, `appConnexions_usermodel`.`logoutFromBrowser` FROM `appConnexions_usermodel` WHERE `appConnexions_usermodel`.`userID` = 'i01E25D45526E14EA0A490D36@AdobeID' ; args=(u'i01E25D45526E14EA0A490D36@AdobeID',)

PlayedGamesModel是与GameModel(appConnexions_gamemodel)UserModel(appConnexions_usermodel)有关系的表格。从playedFromConnexions打印整数值(PlayedGamesModel)会不必要地向GameModelUserModel发送查询。

0 个答案:

没有答案