类型错误:'authors'是此函数的无效键参数

时间:2015-04-25 22:39:23

标签: django python-3.x django-models django-admin

我真的不知道为什么我在这款django应用程序中遇到类型错误。下面是我的models.py代码:

success()

我分别从名为(mak& mas)的shell创建了作者对象和发布者对象。

from django.db import models

# Create your models here.
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=30)
    website = models.URLField()

    def __str__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField(verbose_name=' Your E-mail')

    def __str__(self):
        return "%s %s" %(self.first_name, self.last_name)

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

    def __str__(self):
        return self.title

但是当我尝试填充Book数据库表时,我得到一个类型错误:

>>> from books.models import Publisher, Author, Book
>>> mak = Author.objects.create(first_name = "Kennedy")
>>> mas = Publisher.objects.create(name = "Dreem Inc")

我可以轻松填充“发布者”和“作者”表格。

请对此有任何帮助吗?

1 个答案:

答案 0 :(得分:1)

您不能在模型的构造函数中指定ManyToMany字段。此外,您无法将M2M字段设置为未保存的实例。因此,您必须先保存实例,然后分配M2M字段:

mybook = Author.objects.create(title="The Prince", publisher=mas,
                               publication_date=date(1989, 6, 30))
mybook.authors.add(mak) # or mybook.authors = [mak]