Skip to content Skip to sidebar Skip to footer

Django Model: Generate Series Number For Each Identifier Upon Saving The Model

Good day! I am very new in Django python web development. I have a scenario where I need to automatically generate a property number and a set of series number per location_code as

Solution 1:

I answered this question here: https://stackoverflow.com/a/67174385/2380028

As a reference, this is the answer I posted:

I am answering my own question.

I managed to solved my issues with the below save function. if anyone can improve my solution, it will be appreciated.

Note: This is only applicable to newly added instance via admin site and WILL NOT WORK if the instance are imported via django-import-export. So, that would be the remaining issue for me, to automatically assigned the data_counter for every instance when using the import function in admin site.

Else, will do the assignment manually in the excel file. XD

defsave(self, *args, **kwargs): 
    data_counter = Item.objects.filter(location=self.location).aggregate(counter=Count('id'))['counter'] # Count existing instance with matching "location id" of the new instanceif self.pk isNoneand self.property_number isNone: # if new instance and property number field is blankif data_counter isNone: # if data_counter is empty/none, no matching instance
            data_counter = 1# start at 1else: # else, if there is matching instance
            data_counter += 1# add 1 to the data_counterelif self.pk isnotNoneand self.property_number isNone: # if not new instance and property number field is blank, Update an instance without property numberif data_counter isNone: # if data_counter is empty/none, the existing instance has no matching location id, Update
            data_counter = 1# Existing instance start at 1else: # else, if there is matching instance
            data_counter += 1# add 1 to the data_counter# data_counter will be the series number for every location ID
    self.property_number = '{}-{}-{:04d}-{}'.format(self.date_acquired.year, self.sub_major_group_and_gl_account.sub_major_group_and_gl_account, data_counter, self.location.location_code)
    
    super(Item, self).save(*args, **kwargs)

Post a Comment for "Django Model: Generate Series Number For Each Identifier Upon Saving The Model"