Reputation: 7081
Suppose I have two models, Book and Page, such there is a one-to-many relationship between Page to Book. I would like each Book model, to have a function which creates a bunch of Pages for the respective Book model, but I'm not sure how to associate each Page's foreign key back to the Book instance it was created in.
I currently have an associate function, which finds the correct book amongst all the possible books, and I'm sure there's a better way, but I can't seem to find it. Is it possible to set the foreignkey to self?
Upvotes: 1
Views: 6276
Reputation: 11464
class Page(models.Model):
# default related_name would be `page_set` but `pages`
# seems a bit more intuitive, your choice.
book = models.ForeignKey("yourapp.Book", related_name="pages")
class Book(models.Model):
# ...
# you can use self as the instance and magically you have
# this `pages` attr which is a related manager, like `Page.objects`
# but limited to the particular Book's pages.
def special_page_create(self, *args, **kwargs):
self.pages.create(
# ...
)
# ...
then, you have a book instance, you have a related manager,
book = Book.objects.get(...
book.pages.create(...
page, created = book.pages.get_or_create(...
pages_gte_42 = book.pages.filter(num__gte=42)
# etc
let me know what else you need to know. The reverse relationship is semi-magical; you don't declare anything on the Book class but you get the related manager on the Book
instances.
Upvotes: 4
Reputation: 11322
There is a one-to-many relationship between Book and Page. This means that one Book has several Pages and each Page only one Book.
In a database (and therefore in an ORM mapper) you would model this by creating a foreign key in Page. This foreign key would point to the Book instance that contains these Pages.
If you want to find the Pages for a Book, you'd query the Pages table for all Pages with the same foreign key as the primary key of the Book.
Upvotes: 1
Reputation: 364
would try something like this:
Class Page(models.Model):
#Your fields, like a name or whatever
name = models.CharField(max_length=60)
Book= models.ForeignKey("Book")
Class Book(models.Model):
#Your fields again
def create_page(self):
"Adds a page to the book"
#Do what you need to do
page = Page(name="TitlePage", Book=self)
page.save()
Or something like that... I think the order of the classes is important too.
Upvotes: 2