Using a .csv file stored in django model FileField

Hi everyone,

Can anyone tell me how to use a csv file stored in a django model?

I’d like to access certain columns using a python script called in views. However, when I try to access the file as follows, I get the error that the “FieldFile object is not subscriptable”.

    #access last instance of model
    my_model = ArrayCsv.objects.all().order_by('-id')[0]
    my_csv = my_model.csv_file

    #try action on csv file
    print(my_csv[0])

Alternatively, when I try the following, I get an error: “expected str, bytes or os.PathLike object, not FieldFile”

    #access last instance of model
    my_model = ArrayCsv.objects.all().order_by('-id')[0]
    my_csv = my_model.csv_file
    
    #try to open csv file like a normal python script
    with open(my_csv, newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in spamreader:
            print(', '.join(row))

Is there an established way to do this? Many thanks

From the docs:

When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file.

If you are storing your file on the local disk (and not a service like S3) you can use the built-in FileField method to open the file

If you want to work with the file you can open using the FieldFile. path

my_csv = my_model.csv_file.path

Yes. A FieldFile is an object, not a file. Pay particular attention to what the data types are of every variable at every step of the way.

Start with reading the docs at:

Hi @dwtz and @KenWhitesell

Thanks for your replies!
Got it opened with the .path after your suggestion! I tried .url before and gave up that lead.

Thanks again!