1

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.

SteveV
  • 429
  • 3
  • 8
  • 18

3 Answers3

2

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
rdas
  • 20,604
  • 6
  • 33
  • 46
  • That worked great! Thank you. One point of clarity, what does the asterisk do? – SteveV Oct 01 '19 at 23:02
  • Tuple unpacking: https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/comment-page-1/ – rdas Oct 01 '19 at 23:05
2

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')
)
Alexander
  • 105,104
  • 32
  • 201
  • 196
1

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

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11