一对多django添加作者为书

时间:2019-07-27 11:26:27

标签: django django-models

我有一家书店,我想添加几位作者来添加一本新书。我该怎么办?我的代码只接受一位作者

class Authors(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
class Book(models.Model):
    title = models.CharField(max_length=200)
    topic = models.CharField(max_length=200)
    author = models.ForeignKey(Authors, on_delete = models.DO_NOTHING)

1 个答案:

答案 0 :(得分:1)

您将关系设为ManyToManyField [Django-doc],例如:

class Author(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)

class Book(models.Model):
    title = models.CharField(max_length=200)
    topic = models.CharField(max_length=200)
    authors = models.ManyToManyField(Author)

例如,您可以创建BookAuthor,例如:

sona = Author.objects.create(first_name='Sona', last_name='Charaipotra')
dhon = Author.objects.create(first_name='Dhonielle', last_name='Clayton')

book1 = Book.objects.create(title='Tiny Pretty Things', topic='dance')
book1.authors.add(sona, dhon)
  

注意:模型通常具有单数名称,因此Author而不是 Authors