两个表中的Django ManyToMany CreateView字段 [英] Django ManyToMany CreateView Fields In Both Tables

查看:106
本文介绍了两个表中的Django ManyToMany CreateView字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,分别是Book和Author,我在Book模型中添加了ManyToMany字段

I have two models, there are Book and Author and I add ManyToMany field inside Book model

class Author(models.Model):
    name = models.CharField(verbose_name='name', max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return unicode(self.name)    

class Book(models.Model):
    title = models.CharField(verbose_name='title', max_length=50)
    authors = models.ManyToManyField(Author) # Many to many
    created_at = models.DateTimeField(auto_now_add=True)    

    def __unicode__(self):
        return unicode(self.title)

如果我想从书中创建CreateView并访问作者,则可以添加这样的代码

If I want to create CreateView from book and access authors, I can just add code like this

class BookCreateView(CreateView):
    model = Book
    template_name = "books/book_create.html"
    fields = ['title', 'authors'] 

但是我想问的是我想从Author模型中创建CreateView,并在其中添加名为 books 的字段.我试过这样的代码

but something that I want to ask is I want to create CreateView from Author model and add field named books inside it. I tried to code like this

class AuthorCreateView(CreateView):
    model = Author
    template_name = "books/author_create.html"
    fields = ['name', 'books']

,它显示错误为作者指定了未知字段(书)".

and it shows an error "Unknown field(s) (books) specified for Author".

帮助我的主人,我是django的新手

help me masters, I'm new in django

谢谢:)

推荐答案

由于Author模型没有名为books的字段,因此无法在AuthorCreateView字段中添加该字段.

Since Author model don't have a field named books, you cannot add that in AuthorCreateView fields.

您应该做的是首先创建Author的实例,然后将其添加为book实例中的作者.

What you should do is first create an instance of Author and then add them as author in books instance.

示例.

book_instance.authors.add(author_instance)

这篇关于两个表中的Django ManyToMany CreateView字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆