简体   繁体   中英

Extracting case insensitive words from a list in django

I'm extracting values from a csv file and storing these in a list. The problem I have is that unless there is an exact match the elements/strings don't get extracted. How would I go about a case insensitive list search in Django/Python?

def csv_upload_view(request):
    print('file is being uploaded')

    if request.method == 'POST':
        csv_file_name = request.FILES.get('file')
        csv_file = request.FILES.get('file')
        obj = CSV.objects.create(file_name=csv_file)
        result = []

        with open(obj.file_name.path, 'r') as f:
            f.readline()
            reader = csv.reader(f)
            #reader.__next__()
            for row in reader:
                data = str(row).strip().split(',')
                result.append(data)

                transaction_id = data[1]
                product = data[2]
                quantity = data[3]
                customer = data[4]
                date = parse_date(data[5])

                try:
                    product_obj = Product.objects.get(name__iexact=product)
                except Product.DoesNotExist:
                    product_obj = None
                
                print(product_obj)

    return HttpResponse()

Edit:

the original code that for some reason doesn't work for me contained the following iteration:

for row in reader:
    data = "".join(row)
    data = data.split(';')
    data.pop()

which allows to work with extracted string elements per row. The way I adopted the code storing the elements in a list (results=[]) makes it impossible to access the elements via the product models with Django. The above mentioned data extraction iteration was from a Macbook while I'm working with a Windows 11 (wsl2 Ubuntu2204), is this the reason that the Excel data needs to be treated differently?

Edit 2: Ok, I just found this

If your export file is destined for use on a Macintosh, you should choose the second CSV option. This option results in a CSV file where each record (each line in the file) is terminated with a carriage return, as expected by the Mac

So I guess I need to create a csv file in Mac format to make the first iteration work. Is there a way to make both csv (Windows/Mac) be treated the same? Similar to the mentioned str(row).strip().lower().split(',') suggestion?

If what you're trying to do is simply search for a string case in sensitive then all you gotta do is lower the case of your search and your query (or upper).

Here's a revised code

def csv_upload_view(request):
    print('file is being uploaded')

    if request.method == 'POST':
        csv_file_name = request.FILES.get('file')
        csv_file = request.FILES.get('file')
        obj = CSV.objects.create(file_name=csv_file)
        result = []

        with open(obj.file_name.path, 'r') as f:
            f.readline()
            reader = csv.reader(f)
            #reader.__next__()
            for row in reader:
                data = str(row).strip().lower().split(',')
                result.append(data)

                _, transaction_id, product, quantity, customer, date, *_ = data
                date = parse_date(date)

                try:
                    product_obj = Product.objects.get(name__iexact=product)
                except Product.DoesNotExist:
                    product_obj = None
                
                print(product_obj)

    return HttpResponse()

Then when you're trying to store the data make sure to store it lowercase.

Also, do not split a csv file on , . Instead use the Python's CSV library to open a csv file, since the data might contain , . Make sure to change csv.QUOTE so that it encapsulates everything with " .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM