0

我正在学习 Django,并且已经通过“The Django Book”完成了 Model 的章节,但是没有办法在 ManyToMany 和 ForeignKey 中为以下问题插入值:

在下面这个模型中,我如何插入细节"Author""Publisher"for book name = "The book"withpublication-date = "28/10/2013"

插入值后,我如何返回"Author""Publisher"获取book name = "The book"

class Author(models.Model):
    first_name = models.CharField(max_length = 20)
    last_name = models.CharField(max_length = 20, blank = True)
    email = models.EmailField(blank = True)

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

 class Book(models.Model):
    title = models.CharField(max_length=100)
    publisher = models.ForeignKey(Publisher)
    authors = models.ManyToManyField(Author)
    publication_date = models.DateField()
4

2 回答 2

1

如果书已经在数据库中。只是简单地运行

book_obj = Book.objects.get(title="测试标题")   
author1 = Author.objects.get(name="test author1")
author2 = Author.objects.get(name="test author2")
author3 = Author.objects.get(name="test author3")
book_obj.authors.add(author1, author2, author3)    

同样,如果书已经在数据库中,您可以添加 Publisher。

如果您想创建新的书籍条目。

publisher = Publisher.objects.get(name='测试发布者')
author = Author.objects.get(name='测试作者')
Book.objects.create(title='Title1', publication_date='28/10/2013', authors=author, publisher=publisher)
于 2013-10-28T19:19:58.547 回答
0

假设您要添加 Stephen King 的书 Pet Semetary。在添加图书对象之前,您需要已经拥有发布者和作者实例。然后就很简单了:

publisher = Publisher.objects.get(name='Simon & Schuster')
author = Author.objects.get(name='Stephen King')
new_book = Book(title='Pet Semetary', 
                publication_date='28/10/2013', 
                authors=author, 
                publisher=publisher)
new_book.save()

这是您正在寻找的解决方案吗?

评论更新

如果 book 对象存在,您可以像这样应用它:

# create Author and Publisher:
new_author = Author(first_name='Stephen', last_name='King')
new_author.save()
new_publisher = Publisher(...bla bla...)
new_publisher.save()

# link them to your already existing book instance
book_instance = Book.objects.get(title='Pet Semetary')
book_instance.author = new_author
book_instance.publisher = new_publisher

当然,您应该使用比 new_author 或 book_instance 更少的通用名称,但您明白了

于 2013-10-28T17:54:09.627 回答