Django 带注释的queryset,与模型实例上的属性同名,不起作用
我希望模型实例上始终存在一些属性。但是我还需要在查询集中为一些视图添加注释。这可能吗 伪代码:Django 带注释的queryset,与模型实例上的属性同名,不起作用,django,django-models,django-annotate,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(
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)
最好的方法是什么?我希望名称保持不变。最后使用了不同的名称(注释中的注释\当前\位置) 然后包括这样一个属性:
@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()
哎呀,那是不可能的