Django在管理页面中显示一对多的关系

时间:2013-12-22 01:52:57

标签: python database django

数据库示例:

class Brand(models.Model):
  brand_name = models.CharField(max_length=30


class Model(models.Model):
  brand = models.ForeignKey(Brand)
  model_name =  models.CharField(max_length=30)

现在在管理员

admin.site.register(Brand)

class ModelAdmin(admin.ModelAdmin):
  list_display = ['brand', 'model_name']
  fields = ['model_name', 'brand']
admin.site.register(Model, ModelAdmin)

如何在BrandAdmin页面中显示与该品牌相关的所有型号? 就目前而言,品牌页面仅显示品牌,并未显示与其相关的任何模型。

1 个答案:

答案 0 :(得分:2)

嗯,你最好的选择是django inlines

#admin.py    

class ModelAdmin(admin.ModelAdmin):
  list_display = ['brand', 'model_name']
  fields = ['model_name', 'brand']

class ModelInline(admin.TabularInline):
    model = Model

class BrandAdmin(admin.ModelAdmin):
    model = Brand
    inlines = [
        ModelInline,
    ]


admin.site.register(Brand, BrandAdmin)
admin.site.register(Model, ModelAdmin)