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

664
Vistas
How to show name instad of id in django ForeignKey?

I have a model with a ForeignKey to itself.

models.py

class Person(models.Model):
    name = models.CharField(max_length=20)
    important_name = models.ForeignKey('Person', on_delete=models.SET_NULL, blank=True, null=True, related_name='first', verbose_name='Very Important Name')

    def __str__(self):
        return self.name

    def get_fields(self):
        return [(field.verbose_name, field.value_from_object(self)) for field in self.__class__._meta.fields]

And when i want to show my data with DetailView CBV in view it show id instead of name.

views.py

class DetailPerson(DetailView):
    model = Person
    template_name = 'panel/detail_person.html'

detail_person.html

<table class="table">
    {% for label, value in object.get_fields %}
        <tr>
            <td>{{ label }}</td>
            <td>{{ value }}</td>
        </tr>
    {% endfor %}
</table>

template img

How can i show name instead of id?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Here we can use getattr instead of value_from_object, which will return us the related instance of Person instead of an ID.

    def get_fields(self):
        return [(field.verbose_name, getattr(self, field.name)) for field in self.__class__._meta.fields]

example:

from base.models import Person
a = Person.objects.first()
a.get_fields()

Returns [('ID', 1), ('name', 'Joe'), ('Very Important Name', <Person: Bob>)]

Now, we may access all of Bob's attributes in the template as well, if the need arose.

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