/ books / add_review_to_book上的Django OperationalError

时间:2017-09-06 20:10:42

标签: python django operationalerror

我因为这个错误而被困2天,我是Django的新手,我正在尝试为书籍撰写评论。当我打开评论表单并输入一些文字然后提交之后,我收到此错误 -

OperationalError at /books/add_review_to_book/8
table books_review has no column named book_id.

对我来说一切看起来都没问题代码:

我的models.py

class Book(models.Model):

    user = models.ForeignKey(User, default=1)
    title = models.CharField(max_length=100, null=True)
    author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.title + ' - ' + self.author


class Author(models.Model):
    first_name = models.CharField(max_length=50, null=True)
    last_name = models.CharField(max_length=50, null=True)


class Review(models.Model):
    book = models.ForeignKey('Book', related_name='reviews')
    author = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.text

我的views.py:

def add_review_to_book(request, id):
    book = get_object_or_404(Book, id=id)
    if request.method == "POST":
        form = ReviewsForm(request.POST)
        if form.is_valid():
            review = form.save(commit=False)
            review.book = book
            review.save()
            return redirect('book_detail.html', id=book.id)
    else:
        form = ReviewsForm()
    return render(request, 'books/add_review_to_book.html', {'form': form})

我的forms.py:

class ReviewsForm(forms.ModelForm):

    class Meta:
        model = Review
        fields = ('author', 'text')

我的html格式为add_review_to_book:

{% block content %}
        <hr>
    <a class="btn btn-default" href="{% url 'add_review_to_book' id=book.id %}">Add review</a>
{% for review in book.reviews.all %}
    {% if user.is_authenticated %}
    <div class="review">
        <div class="date">
            {{ review.created_date }}
        </div>
        <strong>{{ review.author }}</strong>
        <p>{{ review.text|linebreaks }}</p>
    </div>
    {% endif %}
{% empty %}
    <p>No comments</p>
{% endfor %}
{% endblock content %}

我删除了迁移并重新制作了它们,当我尝试撰写评论时,我仍然遇到同样的错误。提前谢谢。

编辑:在dbshel​​l中运行.schema books_review后的结果 -

CREATE TABLE IF NOT EXISTS "books_review" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "text" text NOT NULL);

table books_review has no column named book_id :(

1 个答案:

答案 0 :(得分:1)

我可以看到,您没有两个字段bookauthor,可能会破坏迁移,尝试执行下一步:

  1. 转储数据./manage.py dumpdata auth.user > users.json
  2. ./manage.py dumpdata books.book > book.json
  3. 删除sqlite数据库rm db.sqlite3
  4. 删除迁移文件夹rm -rf books/migrations
  5. 重新创建图书\迁移mkdir books/migrations
  6. 创建init.py touch books\migrations\__init__.py
  7. 创建新迁移./manage.py makemigrations
  8. 应用迁移./manage.py migrate
  9. 加载数据./manage.py loaddata *.json
  10. 测试您的代码
  11. 希望对你有所帮助