Signal in Model of Django

66 Views Asked by At

I ask you this question that I cannot find a solution. I am entering records in the Django Admin, so I enter the functions in the model. In my Sample class I add several fields, but the one I have problems with is the "number" field (sample number). In this each time I add a new sample, it adds 1 to the last number, and if the year changes, it returns to zero. So I have this code for the Sample Class:

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}"

The function for the signal is this:

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)

But it throws me the following error:

django.db.utils.IntegrityError: null value in column "number" of relation "lab_sample" violates not-null constraint

I really appreciate a solution, thanks you very much.

1

There are 1 best solutions below

1
On

You can save only models or columns that exist so can you try this:

last = next
last.save()