Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django查询中使用case语句_Python_Django - Fatal编程技术网

Python 如何在Django查询中使用case语句

Python 如何在Django查询中使用case语句,python,django,Python,Django,我正在做一个项目,我必须将PostgreSQL查询转换为Django查询。我的问题是如何使用 select id,name, address_1, address_2, city,county,postcode, case when fuel = 't' then 'Yes' when fuel is null then 'No' else 'No' end as fuel, case when food = 't' then 'Yes'

我正在做一个项目,我必须将PostgreSQL查询转换为Django查询。我的问题是如何使用

select id,name, address_1, address_2, city,county,postcode,
        case when fuel = 't' then 'Yes'
        when fuel is null then 'No' else 'No' end as fuel,
        case when food = 't' then 'Yes'
        when food is null then 'No' else 'No' end as food,
        case when shower = 't' then 'Yes'
        when shower is null then 'No' else 'No' end as shower,
        case when toils = 't' then 'Yes'
        when toils is null then 'No' else 'No' end as toils,spaces, cost
        from park
        where type_id = 3 and state_id in (1,2)
一种方法是使用像这样的extra方法

ModelName.objects.extra(select={"link_id": "case when link_id >0  then -3 else 0 end"})
但我认为这不是最好的办法。还有别的办法吗


谢谢

因为这些值都不依赖于任何复杂的数据库逻辑,所以我将把逻辑移到Python中,并在模型上简单地将它们设置为属性

class MyModel(models.Model):
    ... id, name etc ...
    _shower = models.CharField(db_column="shower")

    @property
    def shower(self):
        return 'Yes' if self._shower else 'No'

。。。等等。

@lanzz我认为,这取决于数据库。如果我迁移数据库,它将不适用于新的数据库