1

I'm tring to display a reverse foreign key on admin list_change:

# models.py
class Person(models.Model):
    id = models.CharField(max_length=50, primary_key=True)

class Book(models.Model):
    person = models.ForeignKey(Person, related_name='samples')
    name = models.CharField(max_length=50)

#admin.py
@admin.register(Person)
class PersonAdmin(CustomAdmin):
    list_display = ('id', 'links')

    def links(self, obj):
        links = obj.book_set().all()
        return mark_safe('<br/>'.join(links))

It's like this other post

I'm using django 1.8 and it fails: Stacktrace:

  File "/venv/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py", line 320, in result_list
    'results': list(results(cl))}
  File "/venv/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py", line 296, in results
    yield ResultList(None, items_for_result(cl, res, None))
  File "/venv/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py", line 287, in __init__
    super(ResultList, self).__init__(*items)
  File "/venv/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_list.py", line 199, in items_for_result
    f, attr, value = lookup_field(field_name, result, cl.model_admin)
  File "/venv/lib/python2.7/site-packages/django/contrib/admin/utils.py", line 278, in lookup_field
    value = attr(obj)
  File "/home/kparsa/boom/myapp/myapp/admin.py", line 299, in links
    link = obj.book_set().all()
  File "/venv/lib/python2.7/site-packages/django/db/models/fields/related.py", line 691, in __call__
    manager = getattr(self.model, kwargs.pop('manager'))
KeyError: u'manager'

Does anyone know how to get this to work properly? Note that I do NOT want to do something like

qres = Book.objects.filter(person__id=obj.id).values_list('id', 'name').order_by('name')
for x, y in qres:
    links.append('<a href="/admin/mypp/book?q=ID{}">{}</a>'\
        .format(x, y))

because it will run many duplicate queries (# of rows).

Community
  • 1
  • 1
max
  • 9,708
  • 15
  • 89
  • 144

1 Answers1

0

The error was the result of the fact that I had used a related_name in the model but instead I was trying to use the default model name. In order to solve the problem of the duplicate queries, I queried for all the results in get_queryset(), stored the results in memcached, then in the "links" method, I just pulled it from the cache. Works great! The only danger here would be getting out of sync when new data is pushed. I put a 100 second timeout on the cache to avoid issues.

max
  • 9,708
  • 15
  • 89
  • 144