Search code examples
pythondjangosqlitefile-uploadmodels

Django make document filing structure + foreign keys


So... I am using django and sqlite3 and am trying to create a file storage system to link in with my database. I have 2 models: patient and appointment where patient has a 1 to many relationship with appointment. Each appointment needs to have multiple files associated with it so i created another model called 'appointmentFiles'. I want each appointment file to be uploaded to the path: patient/appointment/filename.txt . I also want it so that when i select the patient, the list of appointments to select from should be shown. It all sounds a little complex so forgive me if I didn`t explain it well enough. Thanks in advance!


Solution

  • I assume models to be like these:

    class Patient(models.Model):
        name = models.CharField(max_length=100)
        .......
        .......
    
    
    class Appointment(models.Model):
        patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
        .......
        .......
    
    class AppointmentFiles(models.Model):
        appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE)
        ........
        ........
        path = 'uploads/'+ appointment__patient__name + '/' + appointment__id + '/'
        file = models.FileField(upload_to=path)
    

    Now, it will store all files to uploads/patient_name/appointment_number/

    where patient_name and appointment_number will vary for every patient.

    Each file will be save as

    uploads/patient_name/appointment_number/filename.extension