python – Create autocode on table field in Django 3.x Database

Question:

I have this model in the Database: products_package with a code field.

I want to create an auto-incremental Code using this PCKG string plus the record id.

That is, if I create record 25 it should look like this:

Code: PCKG25

Below I created more or less a function so that you understand what I want to do:

  • Get the registry id
  • Get the code string
  • Unify String + Id
  • update the field

I'm pretty new to Python and Django so something is not right in the get_auto_code function.

Summarizing: I want to create an autoincremental code taking into account the string + the id

Here the models.py file:

from django.db import models

class products_package(models.Model):

     __AUTOCODE__ = 'PCKG'

    code = models.CharField(verbose_name="Code", max_length=10, unique=True)
    description = models.TextField(null=True, blank=True, verbose_name="Description")
    pieces = models.FloatField(verbose_name="Pieces")
    product_id = models.ForeignKey(
            products, verbose_name="Product", on_delete=models.CASCADE)
    location_id = models.ForeignKey(
        stock_location, verbose_name="Location", null=True, 


        blank=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.code        


     def get_auto_code(self, **kwargs):
        code = super(products_package, self).get_auto_code(**kwargs)
         code_str = str(self.__AUTOCODE__ + self.id)
         code = self.code = code_str
         return code

Stay tuned to your comments.

Answer:

To do this, regarding the field, ideally you should use signals , specifically the post_save signal.

First we create our signal (ideally, the __AUTOCODE__ attribute should not have underscores, since you imply that it is a special attribute and it is not, better is AUTOCODE , without further ado):

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender = 'my_app.products_package')
def set_auto_code(sender, instance, **kwargs):
    if kwargs.get('created'): # Entramos al if si se ha creado la instancia
        # Actualisamos la instancia
        sender.objects.filter(id = instance.id).update(code = instance.AUTOCODE + str(instance.id))

You can put this signal in your models.py file or in a file called signals.py , but if you want to put it in this one, you will have to make some modifications in some files, but that is another topic.

This way every time an instance is created this signal will be called and will update the code field. So the value of the code field will always be 'PCKG' + id .

(A short explanation of What are signals in Django?, since a signal is a trigger that is automatically called after an event that occurs in the ORM or in the db, for more information visit the Django documentation )


On the other hand, if you only want to "show" the AUTOCODE + id so to speak, simply create a function that returns it (because the signal is somewhat tedious and unnecessary if you are only going to show it in a template or something like that):

class products_package(models.Model):
    AUTOCODE = 'PCKG'

    ...

    def get_autocode(self):
        return self.AUTOCODE + str(self.id)

It will suffice to do the following to obtain the autocode :

>>> instance.get_autocode()
PCKG25

And that would be all, I hope I have helped you.

Scroll to Top