Let's say I have these models.
class AdventureWaypoint(models.Model):
adventure = models.ForeignKey("Adventure", on_delete=models.CASCADE)
waypoint = models.ForeignKey("Waypoint", on_delete=models.CASCADE)
created_timestamp = models.DateTimeField(auto_now_add=True)
class Waypoint(models.Model):
name = models.CharField(max_length=255)
class Adventure(models.Model):
waypoints = models.ManyToManyField("Waypoint", through='AdventureWaypoint', related_name='waypoints')
objects = AdventureManager()
How could I write a manager that annotates first_waypoint
to every queryset?
I tried the following, but unfortunately Subquery
doesn't work as expected. Couldn't use F
as well.
class AdventureManager(models.Manager):
def get_queryset(self):
qs = super(AdventureManager).get_queryset()
first_waypoint = AdventureWaypoint.objects.filter(adventure_id=OuterRef("id")).order_by('created_timestamp').first().waypoint
return qs.annotate(first_waypoint=Subquery(first_waypoint, output_field=models.ForeignKey("Waypoint", on_delete=models.CASCADE, null=True, blank=True)))
Do I have to resort to raw SQL or how can this be done via Django ORM?
Note: I don't want to use @property as I want to use this annotated field in querysets e.g for filtering.