简体   繁体   中英

Django displaying one to many relationship in the admin page

Database example:

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)

Now in admin

admin.site.register(Brand)

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

How can I show in the BrandAdmin page all the models that are associated with the one brand? As it stands right now, the Brand page only shows the brands, it doesn't show any of the models associated with it.

Well, your best choice are 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM