首页 > 解决方案 > 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”的“编号”列中的空值违反非空约束

我非常感谢您的解决方案,非常感谢您。

标签: pythondjangodjango-modelsdjango-3.1

解决方案


您只能保存现有的模型或列,因此您可以尝试以下操作:

last = next
last.save()

推荐阅读