如何在 django 中使用注释函数来满足以下条件?

时间:2020-12-22 05:14:53

标签: django django-models django-queryset

class Surface(models.Model):
     name = models.CharField(max_length=100)
     surface_class = models.ManyToManyField(SurfaceClass, default=None)

class SurfaceGeometry(models.Model):
    surface = models.ForeignKey(Surface, on_delete=models.DO_NOTHING)
    geometry_parameter = models.ForeignKey(SurfaceGeometryParameters, on_delete=models.CASCADE)
    value = models.FloatField()

class SurfaceGeometryParameters(models.Model):
    name = models.CharField(max_length=30, unique=True)

Surface.objects.prefetch_related('surface_class',Prefetch('surfacecorrelationcontroller_set'),Prefetch('surfacegeometry_set')).annotate(height=?).order_by('surface_class__name','-height')

我想从 SurfaceGeomentry 模型中获取高度(值),其中 Height 是来自 SurfaceGeometryParameters 模型的几何参数名称。

I can get a height from SurfaceGeometry like this.
SurfaceGeometry.objects.get(surface__id = 1, geometry_parameter__name__iexact= 'Height')
where surfcace__id's value 1 should come from parent query.

我如何才能做到这一点?

1 个答案:

答案 0 :(得分:0)

经过多次尝试,这个问题的最终答案是

surface_height_query = SurfaceGeometry.objects.filter(surface=OuterRef('pk'),geometry_parameter__name__iexact='Height') \
.values_list('value', flat=True)

return Surface.objects.annotate(height=Subquery(surface_height_query)).order_by('surface_class__name','height')

Django Documentation for the same