Alexander Dunaev
Alexander Dunaev

Reputation: 990

Django admin: how to edit two models with indirect relationship on the single admin view?

I am building a website that will provide user-supplied content in different languages, and there will be different entities like articles, questions/answers, email templates, etc. The following DB schema looks logical to me (a pseudo-code describing my DB):

Item
    id (primary key)

Translation
    item_id (foreign key to Item)
    lang (language code)
    title (string)
    body (string)

Article
    published (datetime)
    visible (boolean)
    item_id (foreign key to Item)

FaqCategory
    item_id (foreign key to Item)

FaqItem
    category_id (foreign key to FaqCategory)
    item_id (foreign key to Item)

... (and so on)

So the general idea is simple:

  1. All translations are stored in a uniform way.
  2. Translations of the single item refer to the same Item.
  3. Each entity that needs translation refers to an Item.

Now I want to create an admin view that would show the item together with all its translations. Unfortunately I cannot use Inlines because they only work with direct relations between objects.

So I need to make something like Inlines at my own—essentially, allow editing different models on the same view. Is that possible with the standard admin templates and classes (of course some subclassing will be needed)? I have found how to override the admin templates, and of course it's easy to extend a change form template and insert anything there, but I have no idea how to supply the data for my extensions. It seems like there is no context in the admin classes… Will I have to make the whole view from scratch?

Upvotes: 1

Views: 478

Answers (1)

Andrea Corbellini
Andrea Corbellini

Reputation: 17751

Instead of using the Item model, you could probably use generic foreign keys so that your models become:

Translation
    item (generic foreign key to Article, FaqCategory or FaqItem)
    lang (language code)
    title (string)
    body (string)

Article
    published (datetime)
    visible (boolean)
    item_id (foreign key to Item)

FaqCategory
    item_id (foreign key to Item)

FaqItem
    category_id (foreign key to FaqCategory)
    item_id (foreign key to Item)

Then, you can use inline model admins.

Upvotes: 2

Related Questions