combine django model with csv file and loop

做~自己de王妃 提交于 2019-12-11 15:49:02

问题


I finally manage to show csv file within html and also bind with django model but I am missing a for loop but couldn't make it work.

        if request.method == 'POST' and request.FILES['csv_file2']:
        myfile = request.FILES['csv_file2']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        data = csv.reader(fs.open(filename, mode='r'))
        lines=[]
        instances = []
        for row in data:
            line = row[0]
            lines.append(line)
            query = line
            instances.append(FP.objects.filter(FP_Item=query))
        pair = zip(lines, instances)
        context = {'pair': pair,
                   }
        return render(request, 'check_fp.html', context)
    return render(request, 'check_fp.html', {})

When I use;

instances = fp.objects.filter(fp_Item=query)

It works but I get only last line information from database and missing previous lines but I need loop this "query" or is there any method like append useable with queryset filter?


回答1:


you need to loop while appending the file:

for instance in FP.objects.filter(FP_Item=query):
 instances.append(instance)


来源:https://stackoverflow.com/questions/49775314/combine-django-model-with-csv-file-and-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!