【问题标题】:Is it possible to cycle through django model object fields?是否可以循环浏览 django 模型对象字段?
【发布时间】:2021-11-20 07:05:57
【问题描述】:

我有一个 user 和 user_profile 模型,并且我允许使用可为空的字段进行注册,因此用户可以稍后填写个人资料,但我希望应用程序在每次登录后检查是否有任何个人资料字段为空。是否可以循环浏览django模型对象字段?

我尝试了下面的代码并得到'uProfile is not iterable'

def profile_Populated(usr):
    for x in usr:
       if x == 'null':
            return False
    return True

if profile_Populated(request.user.uProfile) == True:
        pass
    else:
        return redirect("account:profile_edit")

【问题讨论】:

    标签: django


    【解决方案1】:

    尝试检查记录的__dict__ 中的None 值:

    record = request.user.profile
    
    has_empty_value = any([v in record.__dict__.values() if v is None])
    
    if has_empty_value:
        return redirect('account:profile_edit')
    

    【讨论】:

    • 非常感谢!这行得通,但是您的答案存在一个小语法问题。我不得不将 has_empty_value 从“any(v in record.__dict__.values() if v is None)”翻转到“any([if v is None v in record.__dict__.values()])”...但是不管怎么说,还是要谢谢你。真的很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2022-11-19
    相关资源
    最近更新 更多