带注释的查询集,与模型实例上的属性同名不起作用

时间:2021-04-28 16:19:24

标签: django django-models django-annotate

我希望某个属性始终存在于模型实例中。但是我还需要在某些视图的查询集上对其进行注释。这可能吗?

伪代码:

Friend(models.Model):
   name= models.CharField()

   @property
   def current_location(self):
       return self.friendlocation_set.filter(departure_date=None).order_by(
        '-arrival_date').first()


Location(models.Model):
   name=models.CharField()

FriendLocation(models.Model):
   arrival_date = models.DateField()
   departure_date = models.DateField(blank=True, null=True)
   friend = models.ForeignKey('Friend', on_delete=models.CASCADE)
   location = models.ForeignKey('Location', on_delete=models.CASCADE)

class FriendQueryset(models.Queryset):
    def annotate_current_location(self):

        last_location = Subquery(FriendLocation.objects.filter(
        friend=OuterRef('id'), departure_date=None).order_by('-arrival_date').values('location')[:1])

        return self.annotate(current_location=last_location)

这样做的最佳方法是什么?我想保持名称不变。

1 个答案:

答案 0 :(得分:0)

最终使用了不同的名称(注释中的 annotated_current_location)。

然后包含这样的属性:

@property
def current_location(self):
    if self.annotated_current_location:
        return FriendLocation.objects.get(pk=self.annotated_current_location)
    else:
        return self.friendlocation_set.filter(departure_date=None).order_by(
    '-arrival_date').first()
相关问题