Python:如果不是更新,则更新属性值

时间:2016-02-02 15:29:23

标签: python null sqlalchemy attributes

如果属性不等于None,我想更新SQLAlchemy DB中列的值。

此方法有效,但似乎不遵循DRY主体

def editObject(object_id, name, picture, metaTitle, 
    metaKeywords, metaDescription):

    object = session.query(Object).filter_by(id = object_id).one()

    if name:
        object.name = name
    if picture:
        object.picture = picture
    if metaTitle:
        object.metaTitle = metaTitle
    if metaKeywords:
        object.metaKeywords = metaKeywords
    if metaDescription:
        object.metaDescription = metaDescription

    session.add(object)
    session.commit()

谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用关键字参数和setattr()

def editObject(object_id, **kwargs):

    object = session.query(Object).filter_by(id = object_id).one()

    for attr, value in kwargs.iteritems():
        if value:
            setattr(object, attr, value)

    session.add(object)
    session.commit()

答案 1 :(得分:0)

使用关键字参数setattr和列表理解:

def editObject(object_id, **kwargs):

    object = session.query(Object).filter_by(id = object_id).one()

    [setattr(object, key, value) for key, value in kwargs.items()]

    session.add(object)
    session.commit()

然后当您调用该函数时,例如:

object_id = 1
attributes_to_update = {"name": "smith", "metaKeywords": "handsome_devil"}
editObject(object_id, **attributes_to_update)

在该示例中,只会更新namemetaKeywords