如何在 DJango 管理界面中显示 ForeignKey 反向查找列表? [英] How to I show a list of ForeignKey reverse lookups in the DJango admin interface?

查看:30
本文介绍了如何在 DJango 管理界面中显示 ForeignKey 反向查找列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个模型:

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',)

当我添加一个单元时,我的管理界面工作正常(我可以选择将它分配给哪个客户)但是当我在 DJango 管理界面中创建/编辑一个客户时,它没有列出任何单位可供选择.如何启用该部分中的查找以匹配创建/编辑客户区域中的查找?

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?

推荐答案

默认情况下,ModelAdmin 只会让你管理模型本身",而不是相关的模型.为了编辑相关的 Unit 模型,您需要定义一个InlineModelAdmin" - 例如 admin.TabularInline - 并将其附加到您的 CustomerAdmin.

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

例如,在您的 admin.py 中:

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)

这篇关于如何在 DJango 管理界面中显示 ForeignKey 反向查找列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆