6

Assigning a Django Model's field to a value if it matches a condition.

g = Car.objects.get(pk=1234) g.data_version = my_dict['dataVersion'] if my_dict else expression_false # Do nothing?? 

How do I do nothing in that case? We can't do if conditional else pass.

I know I can do:

if my_dict: g.data_version = my_dict['dataVersion'] 

but I was wondering if there was a way to do inline expression_true if conditional else do nothing.

5
  • Nope, can't do it in Python. Commented Aug 14, 2014 at 23:20
  • 2
    You can always write if my_dict: g.data_version = ... on the same line if you want, but that goes against the Python style. Commented Aug 14, 2014 at 23:22
  • why would you want to do this? ... it doesnt make sense... Commented Aug 14, 2014 at 23:25
  • 1
    The "inline if statement" is properly called a conditional expression; it's not a statement. Commented Aug 14, 2014 at 23:58
  • Possible duplicate of How to write inline if statement for print? Commented Oct 6, 2015 at 21:04

1 Answer 1

9

No, you can't do exactly what you are describing, as it wouldn't make sense. You are assigning to the variable g.data_version... so you must assign something. What you describe would be like writing:

g.data_version = # There is nothing else here 

Which is obviously invalid syntax. And really, there's no reason to do it. You should either do:

if my_dict: g.data_version = my_dict['dataVersion'] 

or

g.data_version = my_dict['dataVersion'] if my_dict else None # or 0 or '' depending on what data_version should be. 

Technically, you could also do:

g.data_version = my_dict['dataVersion'] if my_dict else g.data_version 

if you only want to update g.data_version if your dict exists, but this is less readable and elegant than just using a normal if statement.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.