rabaxabel
rabaxabel

Reputation: 31

obtaining related object from django.db.models.fields.related.ForeignKey

From a model object, I can get a related object shortcut, using the name of the foreign key field:

>>> m1 = Mailbox.objects.get(pk=38)
>>> str(m1.localdomainfk)
'framailx.de'

But if I have the foreign key field instead of its name, I can only get the pk of the related object:

>>> f1 = Mailbox._meta.get_field('localdomainfk')
>>> f1.value_from_object(m1)
7

Can anybody show me, how to get the related object shortcut, if I have only the local object and the foreign key field?

Background is a generic readonly DetailView, where the actual list of fields being displayed depends on the active user (staff user sees all).

This is part of a model mixin:

def get_fields(self, staff):
    l = self.readonly_fields_for_staff if staff else self.readonly_fields
    return [(field.verbose_name, self.get_field_value(field), 
                self.get_related_object_from_field(field))
                        for field in l]

def get_field_value(self, field):
    if field.is_relation:
        return None
    else:
        return self._get_FIELD_display(field)

def get_related_object_from_field(self, field):
    if field.is_relation:
        return getattr(self, field.name, None)
    else:
        return None

The list being returned by get_fields is used by a template.

get_related_object_from_field contains the answer from Muhammad Tahir.

Upvotes: 3

Views: 1611

Answers (1)

Muhammad Tahir
Muhammad Tahir

Reputation: 5174

You can use getattr

m1 = Mailbox.objects.get(pk=38)
f1 = 'localdomainfk'
f1 = getattr(m1, f1)

Upvotes: 2

Related Questions