Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 887
DGDD Avatar asked Dec 19 '22 20:12

DGDD


1 Answers

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)
like image 55
Leandro Avatar answered Dec 22 '22 11:12

Leandro