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?

Issue

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

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)

Answered By – Sumithran

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published