I would like some property to always be there on a model instance. But I also need to annotate it on a queryset for some views. Is this possible?
Pseudo-code:
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)
What is the best way to do this? I'd like to keep the name the same.