0

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?

Manoj Tolagekar
  • 1,816
  • 2
  • 5
  • 22
whitebear
  • 11,200
  • 24
  • 114
  • 237
  • 1
    Does this answer your question? [Setting default value for Foreign Key attribute](https://stackoverflow.com/questions/9311996/setting-default-value-for-foreign-key-attribute) – Abdul Aziz Barkat Nov 15 '22 at 07:35
  • I think you can assign objects to the "default" value. – JDODER Nov 15 '22 at 09:26

2 Answers2

1

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)
ybl
  • 1,510
  • 10
  • 16
0
default=lambda: GraduationYear.objects.get_or_create(year=2022)[0]
Tyler2P
  • 2,324
  • 26
  • 22
  • 31