我在这个错误上被困了 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 %}
我删除了迁移并再次进行了迁移,但当我尝试撰写评论时仍然遇到同样的错误。提前致谢。
编辑:在 dbshell 中运行 .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
:(