简体   繁体   中英

How to transfer file from one model to another model?

  1. I have a model in my django app which stores a file.

  2. I have made another model in the same app to store the files using foreign key from the 1st model.

  3. When a new file arrives in model 1 push the existing file to the model 2, and keep the new file in the model 1 and all the old files in model 2.

Does any one have any idea that how can I implement it.

I've done something similar to this, where I wanted to copy a FileField from one model into another model, without actually copying the file.

Let's imagine you have two models, Model1 and Model2. Model1 stores the current version of your file. Model2 stores past versions. Both have FileFields named file.

Here is what your models.py file might look like:

class Model1(models.Model):
    # ...
    file = models.FileField()

class Model2(models.Model):
    # ...
    file = models.FileField()

When you create a new Model2, you reference the file of Model1, before you change that file.

existing_model1 = ...  # Assume you get the Model1 object somehow.
Model2.objects.create(file=existing_model1.file)
# Now you can change existing_model1.file

By default Django will not overwrite the old file with a new file, so it is safe to change existing_model1.file without changing the old file.

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