Search code examples
djangofilefield

Django - How can I set a Model's field using the existance of a ForeignKey as a condition?


I am trying to create a Django app where there are two main models - Team and Person. A Person can use the app as an User or can belong to a Team, and, in that case, the User will be the Team.

class Team(models.Model):
    name = models.CharField(max_length=50)
    team_user = models.ForeignKey(
        User,
        on_delete = models.CASCADE, 
        null = True, 
        blank = True )

class Person(models.Model):    
    person_user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True)
    team = models.ForeignKey(
        Team, 
        on_delete = models.CASCADE,
        null = True,
        blank = True )

I am trying to develop a File structure like this:

/root
  /Team_01
    /Person_01 (non-User)
      /files.csv
    /Person_02 (non-User)
      /files.csv
  /Person_03 (User)
    /files.csv

I have read the documentation and I was trying to do something with the comment from Evgeni Shudzel in this post, but my problem is that I don't know how to set the file's path for the Person model so that if the Person is member of a Team, the path is "/team_id/person_id" and if not, the "/team_id" part is excluded. The pseudocode I have in mind:

if Person.team exists:
    files = models.FileField(upload_to="TEAM_ID/PERSON_ID/")
else:
    files = models.FileField(upload_to="PERSON_ID/")

How can I implement this pseudocode? Thank you!


Solution

  • You are on correct path. upload_to can point to a function.

    def user_directory_path(instance: Person, filename): 
        # file will be uploaded to MEDIA_ROOT / your path 
        if instance.team:  # 
            return f"team_{instance.team.id}/user_{instance.id}"
        else:
            return f"person_{instance.id}"
    
    # ...
    class Person(models.Model): 
        files = models.FileField(upload_to = user_directory_path)