简体   繁体   中英

How do I properly condense this Python IF statement?

I am pretty new to Python, and trying to find a better way to code this. There has to be a way but just not sure how to do it.

The two queries are essentially the same, so there has to be a way to reduce. Is there a more efficient way to do this?

        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

Sorry if this is a simple question, newbie here.

You can simplify by pulling the argument that differs into the if-statement & putting the common stuff outside.

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

You can use ternary logic to add the tuples.

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

You probably want to replace this:

if set_date is not None:

with this:

if set_date:

Take a look at how Python evaluates the if conditional: 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)

Also, 'is' can give some strange results, it's really for determining if two labels reference the same object or not. Understanding Python's is operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM