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 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)

如何通过让用户访问分数对象?

当我给用户评分对象时,我可以得到笔记。

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

我想使用这样的东西:

y = CustomUser.objects.get(id=7)
x = x.score.all()
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'

您有两个来自Custuususer的外国钥匙到得分。第一个,user_from,没有设置相关的_name,因此使用默认值,即 score_set

x = y.score_set.all()

第二个确实设置了一个相关的_name,因此您可以使用:

x = y.user_to.all()

请注意,这是一个相关名称,因为它指向得分,而不是用户。它可能应该像scores_to_user

最新更新