Speedy
Speedy

Reputation: 120

Django Relation

What is the best way to model something like this in Django?

enter image description here
1)

class Book(models.Model):
    name = models.CharField(max_length=100)


class Author(models.Model):
    name = models.CharField(max_length=100)
    book = models.ForeignKey(Book)

This leads to a OneToMany and a ManyToOne Relationship

2)

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.OneToOneField("Author", related_name="author")


class Author(models.Model):
    name = models.CharField(max_length=100)
    book = models.ForeignKey(Book)

This leads to a OneToMany, ManyToOne, OneToOne Relationship (with an unesecary ManyToOne Relationship)

3)

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.OneToOneField("Author", related_name="+")


class Author(models.Model):
    name = models.CharField(max_length=100)
    book = models.ForeignKey(Book, related_name="+")

This is the closest what i want, but is there any better way?

€dit: Author -> Book should be 1; *, not 0; * but not relevant for this question


UPDATE:

That worked for me:

class Book(models.Model):
    name = models.CharField(max_length=100)


class Author(models.Model):
    name = models.CharField(max_length=100)
    books = models.ManyToManyField(Book, through="AuthorBook")


class AuthorBook(models.Model):
    book = models.OneToOneField(Book)
    author = models.ForeignKey(Author)

Thank you @giaco

Upvotes: 1

Views: 95

Answers (2)

Jan Giacomelli
Jan Giacomelli

Reputation: 1339

Book and Author is ManyToMany relationship while book can have more then one authors and author can write more then one book. Therefore you need table AuthorBook in which you have records with Book and Author ids

Upvotes: 1

lch
lch

Reputation: 2188

You should have an intermediary model between author and book:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ManyToManyField(Person, through='AuthorBook')

class AuthorBook(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)

Upvotes: 1

Related Questions