python - Django模型中的信号
问题描述
我问你这个问题,我找不到解决办法。我在 Django Admin 中输入记录,所以我在模型中输入了函数。在我的示例类中,我添加了几个字段,但我遇到的问题是“数字”字段(样本编号)。每次我添加一个新样本时,它都会在最后一个数字上加 1,如果年份发生变化,它会返回零。所以我有这个示例类的代码:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils import timezone
class Sample(models.Model):
PREST = (
('APS', 'APS'),
('Convenio', 'Convenio'),
('Arancelado', 'Arancelado'),
)
DPTO = (
('LAB', 'LAB'),
('DB', 'DB'),
('DSB', 'DSB'),
('DSO', 'DSO'),
)
dpto = models.CharField(max_length=45, choices=DPTO)
number = models.PositiveIntegerField()
matrix = models.ForeignKey('Matrix', models.DO_NOTHING)
kindsample = models.ForeignKey('Kindsample', models.DO_NOTHING)
sample = models.CharField(max_length=255)
identification = models.CharField(max_length=255, blank=True, null=True)
date = models.DateField(blank=True)
city = models.ForeignKey('City', models.DO_NOTHING)
address = models.CharField(max_length=255, blank=True, null=True)
assays = models.ManyToManyField('Assay')
def __str__(self):
return f"{self.number} - {self.sample}"
信号的功能是这样的:
def save_add(sender, instance, **kwargs):
if Sample.objects.all().exists():
now = timezone.now()
year_sample = Sample.objects.all().last().date.year
last = Sample.objects.all().last().number
if year_sample == now.year:
next = last + 1
else:
next = 1
else:
next = 1
number = next
number.save()
post_save.connect(save_add, sender=Sample)
但这给我带来了以下错误:
django.db.utils.IntegrityError:关系“lab_sample”的“编号”列中的空值违反非空约束
我非常感谢您的解决方案,非常感谢您。
解决方案
您只能保存现有的模型或列,因此您可以尝试以下操作:
last = next
last.save()
推荐阅读
- sas - 将目标区间变量转换为类变量,即 SAS Enterprise Miner 中的 0 和 1
- pdf - Netlify 服务器功能无法处理多部分/表单数据
- powershell - 为什么我必须在访问注册表之前使用 Import-Module
- angularjs - Angular,当用户单击按钮或多次提交时如何处理?
- snowflake-cloud-data-platform - 雪花产品库存的加权平均成本
- amazon-redshift - 查询 ID 在 Redshift 中是否唯一
- python - 如何使用互相关找到两个时间序列之间的滞后
- powershell - 无法将 Azure 存储过程返回的数据导出到 Azure 自动化 Powershell 中的 CSV
- flutter - 我正在使用 onChange 将翻译过程转换为 Flutter 中的文本表单字段。我收到一些错误
- angular - 即使在控制台中也没有错误的空白页面