Default instance for Django model
<p>My questionis:  is there anyway to create a default instance for class Language? Like this : </p>

<pre><code>class Language(models.
     default_instance = Language(name="unknown")
     name = models.CharField(max_length=100)
</code></pre>

<p>so class Student can use this: </p>

<pre><code>class Student(models.Model):
         name = models.CharField(max_length=50)
         language = models.ForeignKey(Language, default = Language.default_instance.pk )
</code></pre>

<p>Thank you!</p>

<p>You could set it by overriding the save method:</p>

<pre><code>#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.get(pk=1) #set to default
        self.language = default_language
    super(Student,self).save(self,*args,**kwargs) # the 'real' save
</code></pre>

<p>See <a href="https://docs.djangoproject.com/en/1.10/topics/db/models/#overriding-model-methods" rel="nofollow">here</a> about overriding the save method.</p>

python django django-models