You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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__那样)。

解决方案
  1. 正确创建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)
    
  2. 修正拼写小问题
    你的Debt模型里ammount拼写错了,应该是amount,虽然不影响当前错误,但建议修正保持规范。

  3. 适配Python版本(可选)
    如果是用Python 3开发,建议把__unicode__换成__str__——Python 3不再使用__unicode__,Django虽然会自动兼容,但统一用__str__更符合现代规范:

    def __str__(self):
        return self.who.user.username
    
  4. 检查其他代码逻辑
    排查一下你代码中其他可能的地方,比如表单提交、视图处理,有没有把用户名字符串直接传给ForeignKey字段的情况,及时修正即可。

内容的提问来源于stack exchange,提问作者Irmantas Želionis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:29:15