[英]Django charfield compose default value
如何將組合的默認值添加到charfield?
例
class Myclass(xxx):
type = models.ForeignKey(somewhere)
code = models.CharField(default=("current id of MyClass wich is autoincremented + type value"))
可能嗎?
為此,您可以覆蓋模型上的save方法。
class MyClass(models.Model):
...
def save(self):
super(Myclass,self).save()
if not self.code:
self.code = str(self.id) + str(self.type_id)
self.save()
有些東西你需要注意,比如把代碼作為一個空白字段,但你明白了。
你應該像Lakshman建議的那樣覆蓋save方法,但是,因為這是默認值而不是blank = False,所以代碼應該有點不同:
Class MyClass(models.Model):
...
def save(self):
if not self.id:
self.code = str(self.id) + str(self.type_id)
return super(Myclass,self).save())
您也可以使用post_save信號
from django.db.models import signals
class MyClass(models.Model):
type = models.ForeignKey(somewhere)
code = models.CharField(blank=True)
def set_code_post(instance, created, **kwargs):
instance.code = str(instance.id) + str(instance.type_id)
instance.save()
signals.post_save.connect(set_code_post, sender=MyClass)
或者,就此而言,您可以使用pre_save和post_save信號的組合來避免運行save()兩次...
from django.db.models import signals
class MyClass(models.Model):
type = models.ForeignKey(somewhere)
code = models.CharField(blank=True)
def set_code_pre(instance, **kwargs):
if hasattr(instance, 'id'):
instance.code = str(instance.id) + str(instance.type_id)
def set_code_post(instance, created, **kwargs):
if created:
instance.code = str(instance.id) + str(instance.type_id)
instance.save()
signals.pre_save.connect(set_code_pre, sender=MyClass)
signals.post_save.connect(set_code_post, sender=MyClass)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.