Home > Net >  How to set the default value for ForeignKey
How to set the default value for ForeignKey

Time:11-15

I have this field

graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False)

and GraduationYear class is.

class GraduationYear(BaseModel):
    label = m.CharField(max_length=255)
    year = m.CharField(max_length=255,unique=True)
    def __str__(self):
        return self.label

Now I want to set the GraduationYear object where year=2022 as the default value of graduation_year

So, I am guessing I should embed sql to here below.

graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False,default='select GraduationYear where year=2022')

Is it possible?

CodePudding user response:

default=lambda: GraduationYear.objects.get_or_create(year=2022)[0]

CodePudding user response:

If your table is only managed using the ORM, a good approach would be to override the __init__ method on the model to set it if not provided:

class GraduationYear(BaseModel):
    label = m.CharField(max_length=255)
    year = m.CharField(max_length=255,unique=True)
    def __str__(self):
        return self.label


class GraduationDetails(BaseModel):
    graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False, blank=False)

    def save(self, *args, **kwargs):
        if not self.graduation_year:
            self.graudation_year, _ = GraduationYear.objects.get_or_create(year=2022)
        return super().save(*args, **kwargs)
  • Related