combine django model with csv file and loop

2019-08-26 17:35发布

问题:

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)