Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

352
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda