Python django.db.models.expressions 模块,CombinedExpression() 实例源码

我们从Python开源项目中,提取了以下1个代码示例,用于说明如何使用django.db.models.expressions.CombinedExpression()

项目:djangocms-association    作者:python-spain    | 项目源码 | 文件源码
def post(self, request, data):
        if not data.get('name') and not data.get('lat'):
            return HttpResponseServerError("Name or coords is required.")
        if data.get('name'):
            model = {'city': City, 'subregion': Subregion, 'region': Region}.get(data.get('model'))
            if not model:
                return HttpResponseServerError("Invalid model: {}".format(data.get('model')))
            obj = get_object_or_404(model, pk=data['name'])
        else:
            # http://stackoverflow.com/a/35079313
            pnt = Point(float(data.get('lon', 0)), float(data.get('lat', 0)), srid=4326)
            order_by_expression = CombinedExpression(F('location'), '<->', GeomValue(pnt))
            try:
                obj = City.objects.order_by(order_by_expression)[0]
            except IndexError:
                return
        fields = ['subregion', 'region', 'region__country', 'country']
        data = {getattr(obj, key).__class__.__name__: {x: getattr(getattr(obj, key), x) for x in ['id', 'name']}
                for key in fields if hasattr(obj, key)}
        if not data.get('name'):
            # Is geo coord search
            data['city'] = {'id': obj.pk, 'name': obj.name}
        if hasattr(obj, 'location'):
            order_by_expression = CombinedExpression(F('location'), '<->', GeomValue(obj.location))
            try:
                data['postal_code'] = PostalCode.objects.order_by(order_by_expression)[0].code
            except IndexError:
                pass
            data['coords'] = obj.location.coords
        return data