L
L
lopatin_ay2015-09-14 19:48:36
Django
lopatin_ay, 2015-09-14 19:48:36

How to make nested ForeignKeys in admin?

Hello, I'm trying to make an analogue of a book, this is how the model looks like: Book -> Subsection -> Paragraph
models.py

# Раздел книги: Механика, Молекулярная, Электричество...
class Book(models.Model):
    book_title = models.CharField(max_length=64, blank=True, null=True)
    book_text = models.TextField()
    
    def __str__(self):
        return self.book_title


# Подраздел книги: Кинематика, Динамика, Статика...
class Section(models.Model):
    section_title = models.CharField(max_length=128, blank=True, null=True)
    section_text = models.TextField()
    section_book = models.ForeignKey(Book)
    
    def __str__(self):
        return self.section_title


# Параграф подраздела: Перемещение, Путь и т.д.
class Paragraph(models.Model):
    paragraph_title = models.CharField(max_length=256, blank=True, null=True)
    paragraph_text = models.TextField()
    paragraph_date = models.DateTimeField()
    paragraph_section = models.ForeignKey(Section)
    
    def __str__(self):
        return self.paragraph_title

On the main page of the admin area, sections are displayed accordingly: Books, Sections, Paragraph. Going into Books, I add new books, going into Sections, I add a new section linked to the book (Books) and Paragraph linked to Sections (section).
Personally, I don’t really like this approach, because with the same 20 paragraphs, you can already get confused about which section it belongs to and which book. I want to do the following: In the Books section (of some book, let's say Mechanics), a list of Sections should be displayed (which correspond to this book: Kinematics, Dynamics ...) and by selecting the Sections we need, we get to a similar page, only now we see paragraph list. I hope I didn't explain too confusingly :)
If it’s clear, then in order to get to editing / adding a new paragraph, we must go this way Books -> Sections -> Paragraph.
Is it possible to do this with the standard django admin tools or can I use other solutions?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pinkevich, 2015-09-14
@pinkevich

https://docs.djangoproject.com/en/1.8/ref/contrib/...
or djbook.ru/rel1.7/ref/contrib/admin/index.html#inli...

I
IvanOne, 2015-09-15
@IvanOne

Here is an example, there is an operation model, and the operation date model clings to it, in the admin panel it looks like this:

class OperationDateInline(admin.TabularInline):
    model = OperationDate

@admin.register(Operation)
class OperationAdmin(admin.ModelAdmin):
    inlines = [OperationDateInline, ]

This is the easiest method to use, there are still a lot of settings, StackedInline and TabularInline The difference between them is only in the template used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question