Django中如何在Debt类__unicode__方法通过ForeignKey返回用户用户名?
你遇到的错误invalid literal for int() with base 10: 'Julius',并不是Debt类的__unicode__方法本身的问题,而是你在创建Debt实例时,错误地把用户名字符串传递给了who或whom字段导致的。
为什么会这样?因为who和whom是指向UserProfile的ForeignKey字段,Django期望你传入的是UserProfile对象或者它的整数ID,而不是用户名字符串。当你传入'Julius'这个字符串时,Django会尝试把它转换成整数(作为UserProfile的主键),自然就会报错了——毕竟'Julius'根本不是整数。
而你的__unicode__方法逻辑是对的:只要who字段正确关联了UserProfile对象,self.who.user.username完全可以正常返回用户名(就像UserProfile的__unicode__那样)。
正确创建Debt实例
创建Debt时,先获取对应的UserProfile对象,再传递给who/whom字段:# 先通过用户名找到对应的UserProfile julius_profile = UserProfile.objects.get(user__username='Julius') # 假设还有另一个用户的Profile another_profile = UserProfile.objects.get(user__username='AnotherUser') # 用UserProfile对象创建Debt new_debt = Debt.objects.create(who=julius_profile, whom=another_profile, ammount=50.0)修正拼写小问题
你的Debt模型里ammount拼写错了,应该是amount,虽然不影响当前错误,但建议修正保持规范。适配Python版本(可选)
如果是用Python 3开发,建议把__unicode__换成__str__——Python 3不再使用__unicode__,Django虽然会自动兼容,但统一用__str__更符合现代规范:def __str__(self): return self.who.user.username检查其他代码逻辑
排查一下你代码中其他可能的地方,比如表单提交、视图处理,有没有把用户名字符串直接传给ForeignKey字段的情况,及时修正即可。
内容的提问来源于stack exchange,提问作者Irmantas Želionis

