'How we can access and save object value of foregn model as default value, if the field is empty while saving the related object model?
class ObjectSEO(models.Model):
object= models.ForeignKey(Objects, related_name='seo', on_delete=models.CASCADE)
meta_description = models.CharField(max_length=170, help_text="Please add product meta description, max length 170 characters", default="Some Texts" )
meta_keywords = models.CharField(max_length=250, help_text="Please add product keywords separated with comma", default="Some Texts" )
meta_name = models.CharField(max_length=70, help_text="object title" default = Objects.name)
Here, I have two models, Objects and ObjectSEO.
In ObjectSEO model > site_name column> I want to add foreign key Objects name as default value.
How can I do this? Is my approach pythonic?
Solution 1:[1]
You can override the save() method of the ObjectSEO model, to set a default value to the model's field itself.
class ObjectSEO(model.Model):
object= models.ForeignKey(Objects, related_name='seo', on_delete=models.CASCADE)
meta_description = models.CharField(max_length=170, help_text="Please add product meta description, max length 170 characters", default="Some Texts" )
meta_keywords = models.CharField(max_length=250, help_text="Please add product keywords separated with comma", default="Some Texts" )
meta_name = models.CharField(max_length=70, help_text="object title" default = Objects.name)
def save(self, *args, **kwargs):
if self.object.name is not None:
self.meta_name = self.object.name
super(ObjectSEO, self).save(*args, **kwargs)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sumithran |
