【问题标题】:Django function include multiple functions with returnDjango 函数包含多个带返回的函数
【发布时间】:2020-07-14 12:21:33
【问题描述】:

我只是想知道在不同模型中进行多次插入的最佳做法是什么

假设我正在收集客户数据,包括

  • 个人信息
  • 地址信息
  • 付款信息

我从一个表单一个视图收集所有这些信息,我想在多个模型(CustomerInfo、CustomerAddress、CustomerPayment)中进行多次插入,如下所示

def insertNewCustomer():

InsertPersonalInfo()
InsertAddressInfo()
InsertPaymentInfo()

return render()



def InsertPersonalInfo(request):
     if request.moethod == 'POST'
        if form.is_valid():
           form.save()
           return ???
     
def InsertAddressInfo(request):
         if request.moethod == 'POST'
        if form.is_valid():
           form.save()
           return ???
def InsertPaymentInfo(request):
     if request.moethod == 'POST'
        if form.is_valid():
           form.save()
           return ???

问题是我在第一个函数中执行插入过程后应该返回什么 InsertPersonalInfo() 再次返回到 insertNewCustomer 并从下一个函数 InsertAddressInfo 继续

我希望我的问题很清楚:D 我应该从嵌套函数返回什么以返回主函数并从调用它的位置继续。

【问题讨论】:

    标签: django function view insert


    【解决方案1】:

    InsertPersonalInfo() 再次返回到 insertNewCustomer

    你可以看看HttpResponseRedirect。官方文档中的一个使用示例如下:

    from django.http import HttpResponse, HttpResponseRedirect
    from django.shortcuts import get_object_or_404, render
    from django.urls import reverse
    
    from .models import Choice, Question
    
    def vote(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        try:
            selected_choice = question.choice_set.get(pk=request.POST['choice'])
        except (KeyError, Choice.DoesNotExist):
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': "You didn't select a choice.",
            })
        else:
            selected_choice.votes += 1
            selected_choice.save()
            return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
    

    这个功能非常有用,你不仅可以重定向,还可以传入额外的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2018-12-05
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多