0

有时ForeignKey字段需要默认值。例如:处理函数django模型字段默认值的最佳方法是什么?

class ReleaseManager(BaseManager): 

    def default(self): 
     return self.filter(default=True).order_by('-modified').first() 


class Release(BaseModel): 
    default = models.BooleanField(default=False) 
    ... 


class Server(models.Model): 
    ... 
    release = models.ForeignKey(Release, null=True, default=Release.objects.default) 

一切都很好,与上面的代码好,直到时机成熟的数据库迁移于是功能默认情况下会导致很大的问题,因为默认的功能不能被序列化。手动迁移可以解决这个问题,但是在一个大型项目中,定期迁移可能是squashed,这会给不知情的人留下一个定时炸弹。

一个常见的解决方法是将默认值从字段移动到模型的保存方法,但如果模型由rest framework之类的东西使用或者在字段中创建期望默认值的表单时会导致混淆。

回答

0

我目前最喜欢的解决方法适用于迁移和其余的框架和其他表单生成。它假定对象管理器提供一个默认的方法,并使用一个专门的ForeignKey的领域得到它:

class ForeignKeyWithObjectManagerDefault(models.ForeignKey): 

    def __init__(self, to, **kwargs): 
     super().__init__(to, **kwargs) 
     self.to = to 

    def get_default(self): 
     return self.to.objects.default().pk 


class Project(SOSAdminObject): 
    primary = ForeignKeyWithObjectManagerDefault(Primary, related_name='projects') 
    ... 

现在迁移按预期工作,我们可以使用任何功能,我们希望提供一个默认的对象为外键字段。

相关问题