0

I have a requirement where a user uploads files to the File collection

class File(Document):
     user = ReferenceField(User)
     file = FileField()
     type = StringField(choices = ('project', 'uploads'))

The user can then submit a file for acceptance to a project. If the file is accepted, it is then copied and stored in the Project collection.

class Project(Document):
     file = ReferenceField(File)

 file = File.objects(id = id)
 copy = File(user = current_user, file = file.file, type = 'project').save()
 Project(file = copy).save()

However, if the user decides to clean out his Uploads folder,

 files = File.objects(user = current_user, type = 'uploads')
 files.delete()

he is prevented from removing files that were submitted to the Project collection. What is the best way to avoid this? Is there a way to copy a file such each file has a 1:1 correspondence with an entry in a collection? Then removing a document from a collection will also remove the file.

spitz
  • 658
  • 1
  • 8
  • 19

1 Answers1

0

Here is my solution. First remove "user" and "type" and add "references" to the File collection. This allows tracking of all references to the specific file.

class File(Document):
     file = FileField()
     references = db.ListField(db.GenericReferenceField())

Now, when a user uploads a file, the user's reference is added to the file's reference list.

file.update(push__references = user)

When a file is used for a project, the project reference is added to the file's reference list.

file.update(push__references = project)

When a user deletes a file, the reference list is checked to see if the user is the only reference. If he is, the file is deleted, if there are additional references, he is pulled from the list and the file is not deleted.

if user in file.references:
     if len(file.references) > 1:
          file.update(pull__references = user)
     else:
          file.file.delete()
          file.delete() 
spitz
  • 658
  • 1
  • 8
  • 19