How to I show a list of ForeignKey reverse lookups in the DJango admin interface?
Asked Answered
U

1

33

I have a couple of models:

class Customer(models.Model):
    customer_name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.customer_name

    class Meta:
        ordering = ('customer_name',)

class Unit(models.Model):
    unit_number = models.IntegerField()
    rentable = models.BooleanField()
    owner = models.ForeignKey(Customer, related_name='units', blank=True, null=True)

    def __unicode__(self):
        return str(self.unit_number)

    class Meta:
        ordering = ('unit_number',)

I have the admin interface working fine when I'm adding a unit (I can select which customer to assign it to) but when I go to create/edit a customer in the DJango admin interface, it doesn't list any units to choose from. How can I enable the lookup in that section to match the one in the create/edit customer area?

Underplot answered 17/4, 2013 at 21:45 Comment(0)
B
75

By default, a ModelAdmin will only let you manage the model "itself", not related models. In order to edit the related Unit model, you need to define an "InlineModelAdmin" - such as admin.TabularInline - and attach it to your CustomerAdmin.

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects

For example, in your admin.py:

from django.contrib import admin
from models import Customer, Unit

class UnitInline(admin.TabularInline):
    model = Unit

class CustomerAdmin(admin.ModelAdmin):
    inlines = [
        UnitInline,
    ]
admin.site.register(Customer, CustomerAdmin)
Boni answered 18/4, 2013 at 2:13 Comment(1)
Is there a way to achieve the reversed result? as in Author data on every photo?Particularly

© 2022 - 2024 — McMap. All rights reserved.