Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

351
Views
Django How to access another object by having a user name?

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'
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!