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

198
Visualizações
__str__ method not being invoked in this django application when calling from foreignkey field

I have this model:

class Country(models.Model):
    name=models.CharField(max_length=100,unique=True)
    createdon=models.DateTimeField(auto_now_add=True)
    updatedon=models.DateTimeField(auto_now=True)

    def __str__(self):
       return self.name

class Guest(models.model):
    nationality=models.ForeignKey(Country,related_name='guest-nation')

in my views.py, I do this:

    guest=Guest.objects.all().values('nationality')

In my template:

     {% for info in guest %}
      {{ info.nationality }}
     {% endfor %}

Now, I am hoping the nationality field to return name of the country but it returns id of the country (as stored in nationality_id) field. From the documentation, I understood it is supposed to return the value specified in the str method.

I can access the name if i the values is nationality__name. It looks uglier than I thought and I am somehow convinced it is supposed to call the str method. Am I wrong?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Try this:

{% for info in guest %}
      {{ info.nationality.name }}
{% endfor %}
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