Python 对象id的Django unicode引发类型错误:强制为unicode
我有一个名为UserProfile的django模型 这是我的密码:Python 对象id的Django unicode引发类型错误:强制为unicode,python,django,unicode,Python,Django,Unicode,我有一个名为UserProfile的django模型 这是我的密码: user_profile = UserProfile.objects.filter(id = 1).first() if user_profile: user_profile_id = user_profile.id user_details = 'user id: ' + unicode(user_profile_id) 代码正常运行,但今天我在第4行最后一行遇到了一个异常: TypeError: co
user_profile = UserProfile.objects.filter(id = 1).first()
if user_profile:
user_profile_id = user_profile.id
user_details = 'user id: ' + unicode(user_profile_id)
代码正常运行,但今天我在第4行最后一行遇到了一个异常:
TypeError: coercing to Unicode: need string or buffer, NoneType found
我不知道这里可能出了什么问题。有时候unicode没有参数,所以像这样更改代码
user_profile = UserProfile.objects.filter(id = 1).first()
if user_profile:
user_profile_id = user_profile.id
if user_profile_id:
user_details = 'user id: ' + unicode(user_profile_id)
我想你的unicode在id中没有得到任何东西,因为它给出了错误,因为用户\u profile\u id id不存在,并将django查询改为.get而不是filter,试着去做except@jahmed31这不应该发生,因为她正在将id传递给Django筛选器。@JohnJosephFernandes如果您正在使用筛选器,并且甚至没有给id,它将给您提供空查询集,因此在这种情况下,如果该对象没有idI,则会给她错误。我看不出这段代码的意义:您显式查询对于id 1,则从结果对象中获取id-但它自然总是1。@如果queryset为None,则if条件将失败。Id是Django模型中的一个必填字段,不能设置为None。我不理解有时unicode获取None参数的含义,我可以添加保护条件,但我需要此错误的确切根源。