Django如何通过用户名访问另一个对象?

Django如何通过用户名访问另一个对象?,django,Django,我有这样的模型: class CustomUser(AbstractUser): selectat = models.BooleanField(default=False) def __str__(self): return self.username class Score(models.Model): VALUE = ( (1, "Nota 1"), (2, "Nota 2"), (3, "Nota

我有这样的模型:

class CustomUser(AbstractUser):
    selectat = models.BooleanField(default=False)

    def __str__(self):
        return self.username


class Score(models.Model):
    VALUE = (
        (1, "Nota 1"),
        (2, "Nota 2"),
        (3, "Nota 3"),
        (4, "Nota 4"),
        (5, "Nota 5"),
        (6, "Nota 6"),
        (7, "Nota 7"),
        (8, "Nota 8"),
        (9, "Nota 9"),
        (10, "Nota 10"),
    )
    user_from = models.ForeignKey(settings.AUTH_USER_MODEL, default=0)
    user_to = models.ForeignKey(settings.AUTH_USER_MODEL, default=0, related_name='user_to')
    nota = models.PositiveSmallIntegerField(default=0, choices=VALUE)

    def __str__(self):
        return str(self.user_to)
如何让用户访问score对象

当我给用户评分对象时,我可以得到注释

x = Score.objects.filter(user_to__username='Fane')
x
<QuerySet [<Punctaj: Fane>, <Punctaj: Fane>]>
for a in x:
    print(a.nota)

1
5
但这行不通,它给了我:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'CustomUser' object has no attribute 'score'

您有两个来自CustomUser的外键用于评分。第一个,user_from,没有设置相关的_名称,因此它使用默认值,即score_set:

第二个设置了相关的_名称,因此您可以使用:

x = y.user_to.all()

请注意,作为一个相关名称,这没有多大意义,因为它指向分数,而不是用户;它应该是类似于分数对用户的关系。

第二种方法有效:你的意思是什么?请注意,这作为一个相关名称没有多大意义,因为它指向分数,而不是用户;可能是分数对用户,我不知道你不明白什么。我的评论是,这个名字没有描述它指向的是什么。aaa,因为它们是用我的语言制作的,我已经改变了一切,所以你可以理解:我也忘了改变它们
x = y.score_set.all()
x = y.user_to.all()