【发布时间】:2018-02-17 16:58:09
【问题描述】:
我不知道向查询集添加数据会如此困难。就像,如果它不是直接来自数据库,那么它也可能不存在。即使我注释,新字段也是二等公民,并不总是可用。
为什么不序列化捕获我的注释字段?
型号
class Parc(models.Model):
# Regular Django fields corresponding to the attributes in the
# world borders shapefile.
prop_id = models.IntegerField(unique=True) # OBJECTID: Integer (10.0)
shp_id = models.IntegerField()
# GeoDjango-specific: a geometry field (MultiPolygonField)
mpoly = models.MultiPolygonField(srid=2277)
sale_price = models.DecimalField(max_digits=8, decimal_places=2, null=True)
floorplan_area = models.DecimalField(max_digits=8, decimal_places=2, null=True)
price_per_area = models.DecimalField(max_digits=8, decimal_places=2, null=True)
nbhd = models.CharField(max_length=200, null=True)
# Returns the string representation of the model.
def __str__(self): # __unicode__ on Python 2
return str(self.shp_id)
查询:
parcels = Parc.objects\
.filter(prop_id__in=attrList)\
.order_by('prop_id') \
.annotate(avg_price=Avg('sale_price'),
perc_90_price=RawAnnotation('percentile_disc(%s) WITHIN GROUP (ORDER BY sale_price)', (0.9,)),
)
geojson = serialize('geojson', parcels)
当我打印 geojson 时,它没有 avg_price 或 perc_90_price 的键/值。在这一点上,我倾向于创建一个虚拟字段,然后在检索查询集后用我的客户计算填充它,但我对想法持开放态度。
class RawAnnotation(RawSQL):
"""
RawSQL also aggregates the SQL to the `group by` clause which defeats the purpose of adding it to an Annotation.
"""
def get_group_by_cols(self):
return []
【问题讨论】:
-
serialize()到底是做什么的? -
获取一个查询集并将其转换为 JSON。具体来说,在这种情况下 geojson 但它忽略了注释字段。我想我会尝试将序列化的字符串转回 JSON 结构,修改它,然后重新序列化。
-
stackoverflow.com/a/25420323/7491209 序列化时似乎不会出现注释。
-
我最终将序列化的字符串转回了一个真正的 json 对象,修改了属性的 subdict,然后重新序列化。