2

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.

gabn88
  • 781
  • 8
  • 23

1 Answers1

0

Ended up using a different name (annotated_current_location in the annotate).

Then included a property like this:

@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()
gabn88
  • 781
  • 8
  • 23