问题描述
我有以下型号:
class Location(models.Model):
system_key = models.CharField(max_length=20,unique=True)
active = models.BooleanField(default=True)
name = models.CharField(max_length=256)
account = models.ForeignKey(Account,on_delete=models.CASCADE)
...
class Locationscores(models.Model):
location = models.ForeignKey(Location,on_delete=models.CASCADE,related_name=LOCATION_scoreS)
date = models.DateField(default=Now)
first_score = models.PositiveSmallIntegerField(default=0)
second_score = models.PositiveSmallIntegerField(default=0)
third_score = models.PositiveSmallIntegerField(default=0)
我正在寻找一种方法来注释某个位置的最新条目中的给定分数列表 最有效(明智的数据库查询)。
由于预取对象无法过滤最新的对象,因此我不想执行以下操作:
locations =Location.objects.filter(account=account).prefetch_related(Prefetch(lookup=LOCATION_scoreS,queryset=Locationscores.objects..order_by('-date'),to_attr='scores_by_date')
))
这可能是一个有效的查询,但由于每个位置可能有数千条记录,并且端点可以为许多位置提供服务,因此内存变得非常大。
所以我尝试使用子查询,我最接近的是:
class LocationscoresManager(models.QuerySet):
def get_latest_location_scores(self,location_scores_names):
scores_query = Locationscore.objects.filter(location=OuterRef('pk')).order_by('-date').values(*location_scores_names)[0]
annotations = {score: Subquery(scores_query)[score] for score in location_scores}
return self.annotate(**annotations)
# adding it to the Location Model:
class Location(models.Model):
# same as before...
scores = LocationscoresManager.as_manager()
scores_list = ['first_score','third_score']
locations = Locations.scores.filter(account=account).get_latest_location_scores(scores_list)
这引发了:
ValueError: This queryset contains a reference to an outer query and may only be used in a subquery.
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)