Home > OS >  How to show name instad of id in django ForeignKey?
How to show name instad of id in django ForeignKey?

Time:12-04

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?

CodePudding user response:

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.

  • Related