Reputation: 2541
I have this in models:
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)
How can i access the score objects by having the user?
When i give the user to score object i can get the notes.
x = Score.objects.filter(user_to__username='Fane')
x
<QuerySet [<Punctaj: Fane>, <Punctaj: Fane>]>
for a in x:
print(a.nota)
1
5
I want to use something like this:
y = CustomUser.objects.get(id=7)
x = x.score.all()
for a in x:
print(a.nota)
1
5
But this won't work, it's giving me:
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'CustomUser' object has no attribute 'score'
Upvotes: 0
Views: 25
Reputation: 599610
You have two foreign keys from CustomUser to Score. The first one, user_from
, does not set a related_name, so it uses the default, which is score_set
:
x = y.score_set.all()
The second does set a related_name, so you use that:
x = y.user_to.all()
Note that this does not make much sense as a related name, since it points to scores, not users; it should probably be something like scores_to_user
.
Upvotes: 1