Django在两个模型中添加表单数据

时间:2016-10-19 09:11:40

标签: django django-models

我正在尝试创建一本新书并根据请求进行审核.POST。这里的问题是问题是数据需要转到带有外键的两个模型。这是request.POST:

def add(request):
if request.method == 'POST':
    result = Review.objects.addBook_and_Review(
        user=request.session['id'],
        title=request.POST['title'],
        author=request.POST['author'],
        new_author=request.POST['new_author'],
        review=request.POST['review'],
        rating=request.POST['rating']
    )
    return redirect('add')
else:
    return render(request, 'books/add.html')

这是自定义管理器和两个模型(Review和Book)。请注意带有外键的Review模型。

class ReviewManager(models.Manager):

   def addBook_and_Review(self, **kwargs):
      #custom manager code here
      return True

class BookManager(models.Manager):
   print('hit book manager')
   pass

class User(models.Model):
   name = models.CharField(max_length=200)
   alias = models.CharField(max_length=200)
   email = models.EmailField()
   pw_hash = models.CharField(max_length=200)
   created_at = models.DateField(auto_now_add=True)
   updated_at = models.DateField(auto_now=True)
   objects = UserManager()

class Book(models.Model):
   title = models.CharField(max_length=200)
   author = models.CharField(max_length=200)
   created_at = models.DateField(auto_now_add=True)
   updated_at = models.DateField(auto_now=True)
   objects = BookManager()

class Review(models.Model):
   review = models.CharField(max_length=1000)
   rating = models.CharField(max_length=200)
   created_at = models.DateField(auto_now_add=True)
   updated_at = models.DateField(auto_now=True)
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   book = models.ForeignKey(Book, on_delete=models.CASCADE)
   objects = ReviewManager()

1 个答案:

答案 0 :(得分:0)

这很容易。如果要使用一个POST请求创建Book和Review对象,请执行以下操作(继续执行代码):

def add(request):
    if request.method == 'POST':
        book = Book.objects.create(
            title=request.POST['title'],
            author=request.POST['author'],
        )

        result = Review.objects.addBook_and_Review(
            user=request.session['id'],
            title=request.POST['title'],
            author=request.POST['author'],
            new_author=request.POST['new_author'],
            review=request.POST['review'],
            rating=request.POST['rating'],
            book=review)
        return redirect('add')
    else:
        return render(request, 'books/add.html')

建议您在使用表单验证后执行此操作。