3

In my django app I create a string which I have to save to my database as a File. If i understand correctly, django is supposed to automatically upload the file when I save the entry:

class Foo(models.Model):
    bar1=models.ForeignKey(Table1)
    bar2=models.ForeignKey(Table2)
    res=models.FileField(upload_to='MYPATH')

The problem is that to create an instance of Foo, I have to first create a physical file on the server's disk which would mean two copies would be created (one by me in order to create a database entry, one by django when saving the entry).

As far as I can see, I must create the file myself in 'MYPATH' and instead of using a FileField, I have to save a reference in the database (essentially what django is doing ????). However I have doubts that this is the best method as

  1. It doesn't strike me as Pythonesque.
  2. I won't have access to the same methods as when using a real FileField. For instance when calling it, I won't have a FieldFile but just a reference string.

Basically, what I wanted to do was: String --> ContentFile (or some form of "virtual" file) --> Physical File handled by Django when saving entry in the database.

entry = Foo(bar1=var1, bar2=var2, res=ContentFile(XMLSTRING))
entry.save()

This doesn't work, but it shows what I want to achieve. So, please show me one of the following three:

  1. How to save a file to the database without physically creating it (using a ContentFile doesn't create a physical file after saving the entry which is what I want to do)
  2. Make django not upload the given file but use the already uploaded version whilst maintaining all the methods provided by FileField
  3. What I don't understand.

I apologize for [my english, my lack of understanding, the lack of clarity]

Anything you need to know, I'd happy to specify.

EDIT: I looked at this thread, but there, the urlretrieve creates a temp file, which is something I don't really want to do. Maybe I should be doing that, but is there a better way?

jsanchezs
  • 1,992
  • 3
  • 25
  • 51
  • To clarify, when executing the given code, an entry is created but its' reference field (here called "res") is empty. And no physical file is created on the disk. – Semptum Valoris Aug 01 '17 at 01:39

0 Answers0