如何使用Ajax和下拉菜单动态过滤查询集

时间:2020-06-15 09:08:52

标签: django django-models django-forms django-views django-templates

我认为以下代码:

def stato_patrimoniale(request):
    now=datetime.datetime.now()
    now=now.year
    ...
    if Ricavi.objects.count()>0:
            for year, month, totale in(Ricavi.objects.values_list( 'data_pagamento_acconto__year', 'data_pagamento_acconto__month').
                annotate(totale=ExpressionWrapper(Sum(F('acconto')),
                output_field=FloatField())).values_list('data_pagamento_acconto__year', 'data_pagamento_acconto__month', 'totale')):
                if id not in incassi.keys() and  year == now:
                    incassi[id]=list(defaults)
                index=month-1
                incassi[id][index]=totale

now变量用于过滤查询集中的数据,其中ricavi是以下模型:

class Ricavi(models.Model):
    codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True, blank=True)
    # numero_lavorazione
    acconto=models.DecimalField()
    data_pagamento_acconto=models.DateField()

现在,我想用一种表格替换now变量,该表格使我可以选择年份并更新我的视图。

我用以下模型创建了另一个应用程序,该应用程序的表单可以添加新年:

class Timing(models.Model):
    reference_year = models.DecimalField(max_digits=4, decimal_places=0, default="2020")

现在,我想创建一个包含所有reference_year填充的下拉按钮,当客户端单击其中一个时,我的now中的def stato_patrimoniale(request):变量将更新。我怎么能达到这个目标?

2 个答案:

答案 0 :(得分:1)

以如下形式插入下拉列表:

<form method="POST" action="url to stato_patrimoniale">
{% csrf_token %}
<select name="year" id="year" onchange="this.form.submit()">
   <option value="2020">2020</option>
   <option value="2019">2019</option>
   <option value="2018">2018</option>  
</select>
</form>

然后在stato_patrimoniale中添加:

 now = now.year
 if request.method == 'POST':
     year = request.POST['year']
     if year != '':
          now = year

答案 1 :(得分:0)

我有这种方式对接收到ajax请求的视图进行编码。

注意:由于我太困倦而无法处理完整的示例哈哈,因此无法显示示例代码

这不是最有效的方法,但是它可以工作,还可以接受多个参数来进行过滤,操作或执行您想做的任何事情。

struct Navbar: View {

    let arView = ARView()

    var body: some View {
        Button(action: {
            //
        }) {
            Image(systemName: "trash")
                .foregroundColor(Color.black)
                .padding()
        }
        .background(Color.white)
    }
}

好吧,在html-js中,我有使用jquery的示例。工作正常,但又不是最理想的方法。

def searchAjaxView(request):
    if request.method == "POST" and request.is_ajax:
        body = json.loads(request.body)
        requestData = {}
        for item in body:
            name = item['name']
            requestData[name] = item
   #all your logic goes here ... 
   #for example read the year
   #Important, check if it exist on the dict before trying to get the value OR always send a default value... in this case im working around the default option in select
   year= requestData['year']['value']
   if year !='':
      #ah idk do your stuff here with the year i'll return a json response
      product_list = list(MyTable.objects.all())
   data = serializers.serialize('json', product_list)
   return JsonResponse(data, safe=False)

如果您的项目越来越大,并且您必须对模板进行许多这种动态更新,那么请考虑使用前端框架或javascript库。两者都更好。