I'm trying to design my first database and got a little bit stuck. The design is as follows: You have an author who can have many books. Each book can have many pages. Each page can have many pictures. Each page is unique (ForeignKey
). Pictures may not be unique (you can use the same picture in different pages/books, so this should be ManyToMany
). My problem is that I can't get the pictures to be a ManyToManyField
when using Inlines
.
If I change ForeignKey to ManyToMany, I get the exception "<class 'books.models.Picture'> has no ForeignKey to <class 'books.models.Page'>
". I had a look here and here, but have no clue how to apply this in my case.
This is how my models.py looks like:
class Author(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=50)
class Page(models.Model):
book = models.ForeignKey(Book)
contents = models.TextField(max_length=15999)
class Picture(models.Model):
page = models.ForeignKey(Page) # ideally, this should be many-to-many
picture_uuid = models.CharField(max_length=36)
In my admin interface, I'd like to have all the books an author wrote on the author page. Also, I'd like to have all pages of a book in the books page and so on. My admin.py therefore looks like this:
class PictureAdmin(admin.ModelAdmin):
list_display = ('id', 'picture_uuid')
class PictureInline(admin.TabularInline):
model = Picture
class PageAdmin(admin.ModelAdmin):
list_display = ('id', 'page_uuid')
inlines = [
PictureInline,
]
class PageInline(admin.TabularInline):
model = Page
class BookAdmin(admin.ModelAdmin):
list_display = ('id', 'title')
inlines = [
PageInline,
]
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'email')
inlines = [
BookInline,
]