首页 > 解决方案 > Django查询中的三元运算符不起作用

问题描述

我想在 django 自定义查询中使用三元运算符,但它会引发异常,下面是我的示例代码:

    def update_cp_generic(self,  customer_profile, defaults, data):
    """
    Update customer profile generic function for Person and Business.

    :param customer_profile: CustomerProfile object.
    :param defaults: dict, params for Person and Business.
    :param data: This is dict for configurations of Business and Person

    :return: The instance of the updated customer profile.
    """
    new_roles = defaults.pop('roles')
    key = 'person' if data['type'] is 'Person' else 'business'
    cp_entity = data['entity'].get_or_create(
        customer_profile=customer_profile,
        **{key: self}
    )
    for attr, value in defaults.items():
        setattr(cp_entity, attr, value)
    deleting_roles = list(set(cp_entity.roles) - set(new_roles))
    self.delete_roles(deleting_roles, customer_profile, cp_entity)
    if cp_entity.id:
        cp_entity.roles = new_roles
        cp_entity.save()
    return self

这是抛出的错误:

TypeError: get_or_create() got an unexpected keyword argument 'person'

我错过了什么吗?

标签: python-3.xdjango

解决方案


'is' 关键字在这里是错误的!

它应该是。

key = 'person' if data['type'] == 'Person' else 'business'


推荐阅读