Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
__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 Respuestas
Responde la pregunta

0

Try this:

{% for info in guest %}
      {{ info.nationality.name }}
{% endfor %}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda