1

I am trying to do a database insert, with a table that has about twenty rows. The insert looks like this:

if not title.name:
    title.name = data['title']
if not title.synopsis:
    title.synopsis = data['synopsis']
...

Basically, I am updating the rows if they don't exist for every db column.

What would be a cleaner, more efficient way to do this?

0

3 Answers 3

3
for column in ('name', 'synopsis', 'something', 'other'):
    if not getattr(title, column):
        setattr(title, column, data[column])
Sign up to request clarification or add additional context in comments.

1 Comment

you should check if hasattr(title,column)
1

Use getattr and setattr functions:

for attribute in ['title', 'synopsis']:
   if not getattr(title, attribute):
       setattr(title, attribute, data[atribute])

You can read more about them here.

Comments

1

You can use or:

title.name = title.name or data['title']
title.synopsis = title.synopsis or data['synopsis']

or alternatively you can do it dynamically:

for attr in data:
    if not getattr(title, attr):
        setattr(title, attr, data[attr])

1 Comment

If data is a dictionary, you don't need to use .keys(). Iterating over a dictionary iterates over its keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.