Django 多对一关系,外键作为文本输入



我有2个数据库,书籍和评论(一本书可以有很多评论,但每个评论只引用一本书(。每个数据库都有一个HTML表单,供用户输入书籍数据或注释。ISBN 是图书数据库的主键和注释数据库的外键。在两种 html 形式中,用户将使用文本输入来输入 ISBN。如何修改下面的 html 表单和代码,以便创建这样的多对一关系?

models.py

class Book(models.Model):
ISBN = models.BigIntegerField(primary_key=True)
Chinese_Book_Name = models.CharField(max_length=200)
English_Book_Name = models.CharField(max_length=200, blank = True)
Author_Name = models.CharField(max_length=100)
class Comment(models.Model):
ISBN = models.ForeignKey(Book, on_delete = models.CASCADE)
age = models.CharField(max_length=10)
score = models.IntegerField()
comment = models.TextField()
topic = models.CharField(max_length=100, blank = True)
name = models.CharField(max_length=50)
contact = models.CharField(max_length=200, blank = True)

Views.py

def saveBook(request):
ISBN = request.POST['ISBN']
Chinese_Book_Name = request.POST['chinese name']
English_Book_Name = request.POST['english name']
Author_Name = request.POST['author name']
book = Book(ISBN = ISBN, Chinese_Book_Name = Chinese_Book_Name, English_Book_Name = English_Book_Name, Author_Name = Author_Name)
book.save()
return redirect('/input/addComment')
def saveComment(request):
ISBN = request.POST['ISBN']
age = request.POST['age']
score = request.POST['score']
topic = request.POST['topic']
name = request.POST['name']
contact = request.POST['contact']
comment = Comment(ISBN=ISBN, age = age, score = score, topic = topic, name = name, contact = contact)
comment.save()
return redirect('/')

正如您在模型中指定的那样,ISBN字段应引用Book对象,而不是字符串;使用这个:

def saveComment(request):
ISBN = request.POST['ISBN']
age = request.POST['age']
score = request.POST['score']
topic = request.POST['topic']
name = request.POST['name']
contact = request.POST['contact']
book = Book.objects.get(ISBN=ISBN)
comment = Comment(ISBN=book, age = age, score = score, topic = topic, name = name, contact = contact)
comment.save()
return redirect('/')

还要记住,正如 Django 所建议的那样,你应该以模型的名称命名你的外键;因此,在这种情况下,最好将(Comment模型的(ISBN字段名称更改为book

相关内容

  • 没有找到相关文章

最新更新