Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Dynamically Access Fields from Foreign Key in Django Admin
    primarykey
    data
    text
    <p>So I have models like this:</p> <pre><code>class Celebrity(models.Model): #30+ fields here ... class HoneyBadger(models.Model): name = models.CharField(max_length=10) celebrity_owner = models.ForeignKey(Celebrity) </code></pre> <p>Now I want the admin interface for HoneyBadger to show the name of the creature plus the celebrity owner fields.</p> <p>I know the standard advice is to do something like this:</p> <pre><code>class HoneyBadger(models.Model): name = models.CharField(max_length=10) celebrity_owner = models.ForeignKey(Celebrity) def owner_birth_date(self): return self.celebrity_owner.birth_date #And so on for every other field in celebrity_owner </code></pre> <p>And then reference those methods in the admin.</p> <p>Instead I want a way to save myself all that typing!</p> <p>Here's my first attempt at a lazy shortcut:</p> <pre><code>class HoneyBadger(models.Model): name = models.CharField(max_length=10) celebrity_owner = models.ForeignKey(Celebrity) def __getattr__(self, name): """Dynamically make derived fields for celebrity_owner fields so I don't have to type out""" field_lookup_prefix = 'celebrity_owner_field_' if name.startswith(field_lookup_prefix): field_name = name[len(field_lookup_prefix):] def wrapper(*args, **kwargs): return getattr(self.celebrity_owner, field_name) return wrapper else: raise AttributeError('%s not found' % name) </code></pre> <p>That does work when I run it in the shell, but the Django admin isn't liking it. I get this error:</p> <pre><code>ImproperlyConfigured at /admin/tracker/ HoneyBadgerAdmin.list_display[5], 'celebrity_owner_field_birth_date' is not a callable or an attribute of 'HoneyBadgerAdmin' or found in the model 'HoneyBadger'. </code></pre> <p>Does anyone know how I can make my code work with the admin or if there's another way to save typing out a method for every single celebrity field? (Perhaps some kind of runtime monkey patching?)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload