Issue
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?
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.