将ImageField URL与Django中的另一个对象相关联

时间:2018-11-08 02:21:25

标签: python django

我有两个模型,

class Core:

    def logo_path(instance, filename):
        pattern = re.compile(r'\s+')
        filename = re.sub(pattern, '', filename)
        return 'images/core/logos/core_{0}/{1}'.format(instance.pk, filename)

    name = models.CharField(db_index=True, max_length=255)
    logo = models.ImageField(upload_to=logo_path, blank=True, null=True)

class CoreRoom(Room):
    core = models.ForeignKey(Core, on_delete=models.CASCADE, null=True)
    logo_url = models.CharField(max_length=1024, null=True)

我想用Core对象中徽标的路径填充CoreRoom对象中的logo_url。 我该怎么做?

2 个答案:

答案 0 :(得分:2)

我怀疑这是必需的。您可以始终使用my_core_room.core.logo.url来访问它,但是最简单的方法是覆盖.save()模型中的CoreRoom方法:

class CoreRoom(Room):
   ...
   def save(self, *args, **kwargs):
       self.logo_url = self.core.logo.url
       super(CoreRoom, self).save(*args, **kwargs)

答案 1 :(得分:1)

logo_url模型字段也可以转换为属性方法,因为不必保存徽标URL信息,因为它已经存储在DB中。例如:

class CoreRoom(Room):
     core = models.ForeignKey(Core, on_delete=models.CASCADE, null=True)
     # remove logo url model field

     @property
     def logo_url(self):
          return self.core.logo.url