【问题标题】:Django - How can I set a Model's field using the existance of a ForeignKey as a condition?Django - 如何使用外键的存在作为条件设置模型的字段?
【发布时间】:2020-11-03 02:39:43
【问题描述】:

我正在尝试创建一个 Django 应用程序,其中有两个主要模型 - 团队和个人。 个人可以作为用户使用应用程序,也可以属于团队,在这种情况下,用户就是团队。

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 )

我正在尝试开发这样的文件结构:

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

我已阅读文档,并试图对 this 帖子中 Evgeni Shudzel 的评论做一些事情,但我的问题是我不知道如何为 Person 模型设置文件路径,这样如果Person 是团队的成员,路径是“/team_id/person_id”,如果不是,则排除“/team_id”部分。我想到的伪代码:

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

如何实现这个伪代码?谢谢!

【问题讨论】:

    标签: django filefield


    【解决方案1】:

    你在正确的道路上。 upload_to 可以指向一个函数。

    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) 
    

    【讨论】:

      猜你喜欢
      • 2010-10-18
      • 2019-11-17
      • 2013-05-23
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 2016-04-30
      相关资源
      最近更新 更多