How to set the default value for ForeignKey

Question:

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?

Asked By: whitebear

||

Answers:

default=lambda: GraduationYear.objects.get_or_create(year=2022)[0]
Answered By: İlyas Sarı

If your table is only managed using the ORM, a good approach would be to override the save 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)
Answered By: ybl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.