我因为这个错误而被困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 %}
我删除了迁移并重新制作了它们,当我尝试撰写评论时,我仍然遇到同样的错误。提前谢谢。
编辑:在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
:(
答案 0 :(得分:1)
我可以看到,您没有两个字段book
和author
,可能会破坏迁移,尝试执行下一步:
./manage.py dumpdata auth.user > users.json
./manage.py dumpdata books.book > book.json
rm db.sqlite3
rm -rf books/migrations
mkdir books/migrations
touch books\migrations\__init__.py
./manage.py makemigrations
./manage.py migrate
./manage.py loaddata *.json
希望对你有所帮助