假设我有这些模型。
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()
我如何编写一个为每个查询集注释first_waypoint
的管理器?
我尝试了以下操作,但不幸的是Subquery
无法按预期工作。也无法使用F
。
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)))
我是否必须求助于原始SQL或如何通过Django ORM做到这一点?
注意:我不想使用@property,因为我想在查询集中使用此带注释的字段,例如进行过滤。
您可以这样尝试(根据documentation):
first_waypoint = AdventureWaypoint.objects.filter(adventure_id=OuterRef("id")).order_by('created_timestamp')
return qs.annotate(first_waypoint=Subquery(first_waypoint.values('waypoint')[:1]))