pieta pieta - 1 year ago 69
Python Question

is there a way to write this if..else statement in one line?

I'm newbie with python and django and now I'm learning how to simplify code in writing the

if ..else
statements in one line.

But in this case I have a two querysets with a little change .
I want to know if it is possible to simlify this code in one line

if self.booked:
x = qs.filter(content_id=content_id, object_id=model.id, action=10)
x = qs.filter(content_id=content_id, object_id=model.id).exclude(action=10)
return x

Answer Source

I would rephrase it so the common parts are outside of the if:

qs = qs.filter(content_id=content_id, object_id=model.id)
return qs.filter(action=10) if self.booked else qs.exclude(action=10)

Although it looks quite cryptic, especially because action 10 is hardcoded. You should define a constant with a clear name for it, at least.

Edit: wow, this is actually wrong, because in one side of the if you filter on content_id, and the other on content_type_id. Is that my bug or yours? At least it's proof that your code is hard to read...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download