0

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

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

对我来说一切都很好,代码如下:

我的模型.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

我的意见.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:(

4

1 回答 1

1

如我所见,您没有两个字段book,并且author可能您破坏了迁移,请尝试执行以下步骤:

  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.pytouch books\migrations\__init__.py
  7. 创建新的迁移./manage.py makemigrations
  8. 应用迁移./manage.py migrate
  9. 加载数据./manage.py loaddata *.json
  10. 测试你的代码

希望对你有帮助

于 2017-09-06T21:31:58.693 回答