为什么不序列化捕获注释字段? [英] Why won't serialize capture annotate fields?

查看:145
本文介绍了为什么不序列化捕获注释字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I had no idea adding data to a queryset would be so hard. It's like, if it didn't come directly from the db then it might as well not exist. Even when I annotate, the new fields are 2nd class citizens and aren't always available.

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

Why won't serialize capture my annotate fields?

型号

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的键/值.在这一点上,我倾向于创建一个虚拟字段,然后在检索到查询集后用客户的计算结果填充它,但我愿意接受想法.

When I print geojson it has no key/values for avg_price or perc_90_price. At this point, I'm leaning towards creating a dummy field and then populating it with the my customer calculations after I retrieve the queryset but I'm open to ideas.

帮助程序类

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和该库中的序列化程序中使用了注释.

I use annotations with Django Rest Framework and the Serializers in that library.

尤其是,序列化方法允许您访问查询集.你可以做这样的事情.

In particular, the serializer method allows you to access the query set. You can do something like this.

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

这篇关于为什么不序列化捕获注释字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆