我创建了一个具有“块”的知识结构,每个块都有适合不同情况的子项。
代码是:
models.py
class KBSBlock(models.Model):
name = models.CharField(max_length=150, unique=True)
code = models.CharField(max_length=4, blank=True)
status=models.CharField(max_length=1, choices=Status_Choices, default='Draft')
enter_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT)
tags = TaggableManager(blank=True)
attribute1 = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
if self.code is None or self.code == "":
self.code = create_code4(self)
super(KBSBlock, self).save(*args, **kwargs)
@receiver(post_save, sender=KBSBlock)
def create_block(sender, instance, created, **kwargs):
if created:
#create_block = BlockDetails.objects.create(block_dts=instance)
print('Working!')
class BlockDetails(models.Model):
block_dts = models.ForeignKey('KBSBlock', on_delete=models.CASCADE)
code = models.CharField(max_length=2, blank=True)
attribute1 = models.CharField(max_length=100, default='All')
created_at = models.DateTimeField(auto_now_add=True)
enter_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT)
status=models.CharField(max_length=1, choices=Status_Choices, default='Draft')
每当我创建一个块时,我都想在BlockDetails中为该块创建一个通用细节,其代码为(code = '00',attribute1 ='All',enter_by ='request.user')
它打印出“工作”位,并散列了“ create_block”行。
我正在使用PostgreSQL,Django 2.1和Python 3.7,无法正确使用它。
请帮助
答案 0 :(得分:0)
首先感谢@ Dani Herrera和@ Davit Tovmasyan!在他们两个之间,我弄清楚了问题所在:原来我有几处错误。
该错误来自数据库:value too long for type character varying(1)
告诉我,我试图输入对于预期字段而言太长的字符串。此字段是状态字段-看起来,即使选择选项在正常情况下也能正常工作, signal命令只需要选择的简短形式。
正确的代码如下:
@receiver(post_save, sender=KBSBlock)
def create_block(sender, instance, created, **kwargs):
if created:
instance.blockdetails_set.create(block_dts=instance.name, code='00', enter_by=instance.enter_by, attribute1='All', status='D')
注意:模型名称的大小写必须小写,即使模型类中的字母大写也是如此
我纠正了这一点-一切正常。