0

我的models.py是

class Book(models.Model):
    book_name=models.CharField(max_length=30)
    author_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    def __unicode__(self):
        ..........

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()

    def __unicode__(self):
        ........

    def books(self):
        return Book.objects.filter(author=self)

我需要从两个不同的模型将数据插入数据库。我需要views.py 示例,因为我使用的代码不能正常工作。请帮我解决一下这个。我正在使用 Django。我使用作者作为 fireign 键,因此应该自动设置,这也不会发生

4

1 回答 1

0
def add_author(request):
    if request.method == 'POST':
        fname = request.POST.get('fname')
        lname = request.POST.get('lname')
        email = request.POST.get('email')
        age = request.POST.get('age')

        author = Author(
            first_name = fname,
            last_name = lname,
            email=email,
            age=age
            )
        new_author = author.save()

        book = request.POST.get('book')
        publisher = request.POST.get('publisher')

        fullname = "{0} {1}".format(new_author.first_name, 
                                    new_author.last_name)

        Book.objects.create(
            book_name=book, 
            author_name=fullname, 
            publisher_name=publisher
            author = new_author
            )

    return render(request, 'add_author.html')

add_author.html

<form method="post">
    {% csrf_token %}
    <h5>Author Info: </h5>
    First name: <input type="text" name="fname"><br/>
    Last name: <input type="text" name="lname"><br/>
    Email: <input type="text" name="email"><br/>
    Age: <input type="text" name="age"><br/>

    <h5>Book Info: </h5>
    Name: <input type="text" name="book"><br/>
    Publisher: <input type="text" name="publisher"><br/>

    <input type="submit" value="Save">
</form>
于 2013-03-02T13:13:31.910 回答