I’m totally new to django, coming from a PHP perspective. I want to write a real basic application with four classes: Book, Ebook, Genre and price. Each Book and Ebook should have one genre and many prizes. In a SQL-DB I’d put a field in Book and Ebook referencing to a genre table by id and a new table called something like Book_prices which is linking Books and Ebooks to prices.
table book_prices
id | type | price
---+--------+------
1 | book | 3
2 | book | 3
3 | ebook | 1
table book/ebook
id | ... | genre_id
---+-----+---------
1 | | 5
2 | | 7
3 | | 9
Basically I want to add a list of prices and ONE genre for each Ebook and Book. How can I do this using the django model? I know of model.ForeignKey() which could be applied to each Book/Ebook referencing to a genre. But what about my prices? If I add a ForeignKey() to a price it can only reference to a Book OR Ebook.
class Book:
name = models.CharField(max_length=100)
pages = models.IntegerField()
class Ebook:
name = models.CharField(max_length=100)
filesize = models.FloatField()
class Genre:
name = models.CharField(max_length=100)
info = models.TextField()
class Price:
currency = models.CharField(max_length=4)
amount = models.FloatField()
Here’s one way. It uses inheritance to reduce duplication between classes.
It uses the contenttypes framework.
Also your classes need to subclass
django.db.models