django - 为什么不序列化捕获注释字段?

标签 django geojson annotate

我不知道将数据添加到查询集会如此困难。就像,如果它不是直接来自数据库,那么它也可能不存在。即使我注释,新字段也是二等公民,并不总是可用。

为什么不序列化捕获我的注释字段?

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/

相关文章:

python - 在 django cms 中以多种语言提供页面的最佳方法

javascript - 在未定义的传单 js ("cannot read property ' 上创建的图层上使用 dblclick 事件时出现问题”)

javascript - 如何修改或删除 GeoJSON Leaflet 对象中的某些现有数据?

django - 如何使用 annotate() 计算 Django 中相关模型的子集?

python - Django 1.8 使用 gmail SMTP 发送邮件

python - 如何将主页添加到 Django 站点地图?

python - 外键问题

javascript - Openlayers 3 geojson 与矢量源

python - matplotlib 的自定义箭头样式,pyplot.annotate

python - 当 x 轴和 y 轴为文本时注释数据点 matplotlib