Reputation: 312
I have a model that has two main classes.
The first is the book model and the second is the page model
The pages have a foreign key field to the books which lets me access them but what I am curious about is, how would you implement page numbers such that when creating a new page object, the number is limited only to be within the current length of pages? Furthermore, if it is inserted, how would you shift the following pages down one in number?
Right now I just have an integer field that I manually type in the page number but if I want to allow users to add pages themselves later, that won't do.
UPDATED:
class Textbook(models.Model):
founder = models.CharField(max_length=256)
title = models.CharField(max_length=256)
cover = models.ImageField(upload_to=get_image_path,
blank=True,
null=True)
def __str__(self):
return self.title
class Page(models.Model):
textbook = models.ForeignKey(Textbook, related_name="pages")
page_title = models.CharField(max_length = 256)
def __str__(self):
return self.page_title
class Section(models.Model):
page = models.ForeignKey(Page,related_name="sections")
section_title = models.CharField(max_length=256)
text = RichTextField(config_name='awesome_ckeditor')
def __str__(self):
return self.section_title
So above is my model, what I am trying to do is make it so that you can keep track of pages, which are contained in TextBook
s, in order. Furthermore, you can insert a new page and the page numbers will change accordingly. So if you say have pages 1,2,3 and want to add a new one, you can add a new one as page 4, or insert it in between 2 and 3 and the former page 3 becomes page 4.
Upvotes: 2
Views: 62
Reputation: 82450
This is a rather improvised solution that I came up with a long time ago, but you might give it a go. What you can do is to use a CharField
.
So for example, you have a book with the following pages:
1 1.1 2 2.1 2.11 2.111 3 4 5 6 7 8.11
When you insert a new page into the book just add another 1
to the end of the page number or decimal field. Then you can just occasionally run a maintenance task to just clean up all the numbers back to 1 2 3 4
, so that you can routinely discard the extra decimals.
You can take a look at the following python code:
In [2]: l
Out[2]: ['1', '2', '3', '4', '4.1', '4.11', '4.11', '5', '6', '1.1']
In [3]: sorted(l)
Out[3]: ['1', '1.1', '2', '3', '4', '4.1', '4.11', '4.11', '5', '6']
In [4]: l.append('5.1')
In [5]: sorted(l)
Out[5]: ['1', '1.1', '2', '3', '4', '4.1', '4.11', '4.11', '5', '5.1', '6']
You can create a routine task, using a django management command to run every once in a while in the background.
Upvotes: 0
Reputation: 311
Does the 'order_with_respect' option the answer at your question:
https://docs.djangoproject.com/en/1.10/ref/models/options/#order-with-respect-to
Upvotes: 1