我的问题:是否有为类语言创建默认实例?像这样:
class Language(models.
default_instance = Language(name="unknown")
name = models.CharField(max_length=100)
所以上课学生可以使用这个:
class Student(models.Model):
name = models.CharField(max_length=50)
language = models.ForeignKey(Language, default = Language.default_instance.pk )
谢谢!
答案 0 :(得分:2)
您可以通过覆盖保存方法来设置它:
#your model
class Student(models.Model):
name = models.CharField(max_length=50)
language = models.ForeignKey(Language)
# override save
def save(self,**args,**kwargs):
if self.language is None:
default_language = Language.objects.get(pk=1) #set to default
self.language = default_language
super(Student,self).save(self,*args,**kwargs) # the 'real' save
请参阅here有关覆盖保存方法的信息。