如何正确压缩这个Python IF语句?

2024-09-28 21:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还很陌生,正在尝试找到一种更好的方法来编写代码。一定有办法,只是不知道怎么做

这两个查询本质上是相同的,因此必须有一种方法来减少。有没有更有效的方法

        if set_date is not None:

            if is_rejected != 'true':
                query = query\
                    .filter(createddate__lte=set_date) \
                    .car_statuses(CarTow.TOWED) \
                    .order_by('-createddate')
            else:
                query = query\
                    .filter(createddate__lte=set_date) \
                    .car_statuses(CarTow.TOWED,CarTow.CONFIRMED) \
                    .order_by('-createddate')

            return query

抱歉,如果这是个简单的问题,新手


Tags: 方法datebyifisorderfilterquery
3条回答

您可以通过将不同的参数拉入if语句来简化;把普通的东西放在外面

if set_date is not None:
       if is_rejected != 'true':
             car_statuses = (CarTow.TOWED,)
       else:
             car_statuses = (CarTow.TOWED, CarTow.CONFIRMED)

       query = query\
           .filter(createddate__lte=set_date) \
           .car_statuses(*car_statuses) \
           .order_by('-createddate')
      return query

您可能要替换此:

if set_date is not None:

有了这个:

if set_date:

看看Python是如何计算if条件的: Truth Value Testing (pydocs)

Here are most of the built-in objects considered false: constants defined to be false: None and False. zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1) empty sequences and collections: '', (), [], {}, set(), range(0)

另外,“is”会给出一些奇怪的结果,它实际上是用来确定两个标签是否引用同一个对象的。 Understanding Python's is operator

您可以使用三元逻辑来添加元组

query = (
    query
    .filter(createddate__lte = set_date) 
    .car_statuses((CarTow.TOWED,) + ((CarTow.CONFIRMED,) if is_rejected == 'true' else ()) 
    .order_by('-createddate')
)

相关问题 更多 >