目前,我正在嵌套循环中执行以下操作: 广告系列= Campaign.objects.get()对于广告系列中的广告系列:职位= campaign.position_set.all()对于以下职位的职位:交易= position.trade_set.all()# 做东西 这可以正常工作,但是在命中数据库的次数方面效率很低.我有更好的方法吗?是与 select_related 相似的东西,但相反吗?一种进行大型查询的方法,可以获取所有广告系列以及相关的头寸和交易,而不必逐一遍历.解决方案由于评论中的建议,我最终得到了以下可行的解决方案: open_campaigns = list(Campaign.objects.prefetch_related(预取('position_set',queryset = Position.objects.all(),to_attr ='cached_positions'),预取('cached_positions__trade_set',to_attr ='cached_trades'),).filter(exit_datetime__isnull = True)) 编辑:应在此导入中添加来自django.db.models的 导入Prefetch 参考预取文档 I have the following model:class Campaign(models.Model): some_campaign_field = models.CharField()class Position(models.Model): campaign = models.ForeignKey(Campaign) some_position_field = models.CharField()class Trade(models.Model): position = models.ForeignKey(Position) some_trade_field = models.CharField()In other words, I have Campaigns which can have multiple Positions. In turn each position within the campaign can have multiple Trades.Is there an efficient way (ie: minimal database calls) to select a Campaign along with all of its associated Positions and Trades. It doesn't look like I can use select_related because that only works the other way, eg: for a specific Trade, select_related will get all of the associated Positions.Currently I am doing this in nested loops as follows:campaigns = Campaign.objects.get()for campaign in campaigns: positions = campaign.position_set.all() for position in positions: trades = position.trade_set.all() # do stuffThis works correctly but is very inefficient in terms of how many times the database gets hit. I there a better way to do this? Something along the lines of select_related but in reverse? A way to do one large query to get all Campaigns along with the associated Positions and Trades without having to loop through each individually. 解决方案 Thanks to the suggestions in the comments, I ended up with the following working solution:open_campaigns = list(Campaign.objects.prefetch_related( Prefetch('position_set', queryset=Position.objects.all(), to_attr='cached_positions'), Prefetch('cached_positions__trade_set', to_attr='cached_trades'), ).filter(exit_datetime__isnull=True))Edit: it should be added this importfrom django.db.models import PrefetchRef. Prefetch docs 这篇关于Django select_related相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-08 17:11