如何在__unicode__返回中从ForeignKey返回用户的用户名?

时间:2018-01-26 15:23:44

标签: python django

我正在尝试在Debt类unicode方法中返回用户的用户名。

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    balance = models.FloatField(default=0.0)

    def __unicode__(self):
        return self.user.username // this one works

class Debt(models.Model):
    who = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="who")
    whom = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="whom")
    ammount = models.FloatField(null=True)

    def __unicode__(self):
        return self.who.user.username //this one does not work

但是,return self.who.user.username会出现invalid literal for int() with base 10: 'Julius'错误。错误在哪里?

1 个答案:

答案 0 :(得分:1)

数据库中的who_id列存储了'Julius'等字符串。这与模型中的外键不同步--Dangang希望它包含整数。