问题描述
我希望某个属性始终存在于模型实例中。但是我还需要在某些视图的查询集上对其进行注释。这可能吗?
伪代码:
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)
这样做的最佳方法是什么?我想保持名称不变。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)