- I have created two models, 1st is Book and 2nd is SubBookPart (Sub Part of Book)
- User creates a book first
- then add its sub part like "Chapter 1", "Chapter 2" and so on to that book
- then add "Page 1", "Page 2" and so on to each chapter
- then add "Paragraph 1", "Paragraph 2" and so on to each Para
- I successfully does this
- My Book Look Like This
BookName
|- Chapter 1
|- Page 1
|- Paragraph 1
|- Paragraph 2
|- Paragraph 3
|- Page 2
|- Paragraph 1
|- Paragraph 2
|- Paragraph 3
|- Chapter 2
|- Page 1
|- Paragraph 1
|- Paragraph 2
|- Paragraph 3
|- Page 2
|- Paragraph 1
|- Paragraph 2
|- Paragraph 3
|- Page 3
|- Paragraph 1
|- Paragraph 2
|- Paragraph 3
But I dont know how to show it in frontend, because it will take very very long nested for loop, Is There and other way
models.py
class Book(models.Model):
name = models.CharField(max_length=50)
subparts = models.ManyToManyField("SubBookPart", related_name="book_subparts", blank=True)
class SubBookPart(models.Model):
# for only first sub part
subpart_of_book = models.ForeignKey(Book, on_delete=models.CASCADE,null=True, blank=True)
# for only non-first sub parts, giving reference to previous subpart
subpart_of = models.ForeignKey("SubBookPart", on_delete=models.CASCADE, null=True, blank=True)
# subpart name like chapter, page, paragraph, line and so on
subpart_name = models.CharField(max_length=50)
# title like chaptername, para 2, page 4, line 5 etc
title = models.CharField(max_length=50)
# if this subpart contains more sub parts, this is used when book has many sub divisions
subparts = models.ManyToManyField("SubBookPart", related_name="sub_subparts", blank=True)
bookview.html
{{book.name}}
<ul>
{% for part in book.subparts.all %}
<li>{{part}}</li>
<ul>
{% for firstpart in part.subparts.all %}
<li>{{firstpart}}</li>
<ul>
{% for secondpart in firstpart.subparts.all %}
<li>{{secondpart}}</li>
<ul>
{% for thirdpart in secondpart.subparts.all %}
<li>{{thirdpart}}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
{% endfor %}
</ul>
{% endfor %}
</ul>