我不知道将数据添加到查询集会如此困难。就像,如果它不是直接来自数据库,那么它也可能不存在。即使我注释,新字段也是二等公民,并不总是可用。
为什么不序列化捕获我的注释字段?
Model
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)
Query:
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 的键/值。在这一点上,我倾向于创建一个虚拟字段,然后在检索查询集后用我的客户计算填充它,但我愿意接受想法。
Helper class
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 []
最佳答案
我将注释与 Django Rest Framework 和该库中的序列化程序一起使用。
特别是,序列化程序方法允许您访问查询集。你可以做这样的事情。
class SomeSerializer(serializers.ModelSerializer):
avg_price = serializers.SerializerMethodField()
def get_avg_price(self, obj):
try:
return obj.avg_price
except:
return None
http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
关于django - 为什么不序列化捕获注释字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46122016/