如果在保存相关对象模型时字段为空,我们如何访问外部模型的对象值并将其保存为默认值?
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)
在这里,我有两个模型,Objects 和 ObjectSEO。
在 ObjectSEO 模型 > site_name 列> 我想添加外键对象名称作为默认值。
我该怎么做?我的方法是 Pythonic 的吗?
您可以覆盖 ObjectSEO 模型的 save() 方法,为模型的字段本身设置默认值。
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)
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)
在这里,我有两个模型,Objects 和 ObjectSEO。
在 ObjectSEO 模型 > site_name 列> 我想添加外键对象名称作为默认值。
我该怎么做?我的方法是 Pythonic 的吗?
您可以覆盖 ObjectSEO 模型的 save() 方法,为模型的字段本身设置默认值。
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)