Django模型:保存模型后,为每个标识符生成序列号 [英] Django model: Generate series number for each identifier upon saving the model

查看:123
本文介绍了Django模型:保存模型后,为每个标识符生成序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!

我是Django python网络开发的新手.我有一种情况,我需要自动生成一个属性号和每个 location_code 的一组系列号作为属性标签的一部分.

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 part of a property tag.

格式为 0000-00-00-0001-000000000 ,格式定义为'year'-'gl_account'-'sub_account'-'series_number'-'location_code'

示例:

位置代码:000000001-办公室

2021-10-10-0001-000000001-表

2021-10-10-0001-000000001 - table

2021-10-10-0002-000000001-椅子

2021-10-10-0002-000000001 - chair

2021-10-10-0003-000000001-计算机集

2021-10-10-0003-000000001 - computer set

位置代码:000000002-仓库办公室

2021-10-10-0001-000000002-表

2021-10-10-0001-000000002 - table

2021-10-10-0002-000000002-长桌

2021-10-10-0002-000000002 - long table

2021-10-10-0003-000000002-咖啡机

2021-10-10-0003-000000002 - coffee maker

以此类推

我已经可以使用除 series_number 之外的部分属性编号来保存模型.我看到您可以生成随机数或字符串,但这不是我所需要的.到目前为止,这是我所拥有的.

I can already save the model with some part of the property number except the series_number. I see that you can generate random numbers or string, but it is not what I need. below is what I have, so far.

class Item(models.Model):

item                    = models.CharField(max_length=100, null=True)
description             = models.TextField(max_length=200, null=True)
date_acquired           = models.DateField(max_length=10, null=True)
old_property_number     = models.CharField(max_length=100, null=True)
property_number         = models.CharField(max_length=100, null=True, blank=True)
unit_of_measure         = models.ForeignKey('Uom', related_name='uom_item', null=True, on_delete=models.SET_NULL)
unit_value              = models.DecimalField(max_digits=12, decimal_places=2, null=True)
quantity_per_card           = models.CharField(max_length=100, null=True, default='1')
quantity_per_physical_count = models.CharField(max_length=100, null=True, default='1' )
location                    = models.ForeignKey('Location', related_name='location_item', null=True, on_delete=models.SET_NULL)
condition                   = models.ForeignKey('Condition', related_name='condition_item', null=True, on_delete=models.SET_NULL)
acountable_person           = models.ForeignKey('Personnel', related_name='personnel_item', null=True, on_delete=models.SET_NULL)
remarks                     = models.ForeignKey('Remarks', related_name='remarks_item', null=True, on_delete=models.SET_NULL)
sub_major_group_and_gl_account    = models.ForeignKey('Account', related_name='sub_major_group_and_gl_account_item', null=True, on_delete=models.SET_NULL)


class Meta:
    verbose_name_plural = 'Item'

def __str__(self):
    return '%s - %s - %s' % (self.property_number, self.item, self.description)

# This is where I override the save function to save the format in the 'property_number' field #
def save(self, *args, **kwargs):
    self.property_number = '{}-{}-{}-{}'.format(self.date_acquired.year, self.sub_major_group_and_gl_account.sub_major_group_and_gl_account, 'series_number', self.location.location_code)
    super(Item, self).save(*args, **kwargs)

管理站点:

推荐答案

我在这里回答了这个问题: https://stackoverflow.com/a/67174385/2380028

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.

我设法通过下面的 save 功能解决了我的问题.如果有人可以改善我的解决方案,将不胜感激.

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

注意:这仅适用于通过管理站点新添加的实例,如果实例是通过django-import-export导入的,则将不起作用.因此,对我来说,这是剩下的问题,在管理站点中使用导入功能时,为每个实例自动分配 data_counter .

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.

否则,将在excel文件中手动进行分配.XD

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

def save(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 instance
    if self.pk is None and self.property_number is None: # if new instance and property number field is blank
        if data_counter is None: # if data_counter is empty/none, no matching instance
            data_counter = 1  # start at 1
        else: # else, if there is matching instance
            data_counter += 1 # add 1 to the data_counter
    elif self.pk is not None and self.property_number is None: # if not new instance and property number field is blank, Update an instance without property number
        if data_counter is None: # if data_counter is empty/none, the existing instance has no matching location id, Update
            data_counter = 1 # Existing instance start at 1
        else: # 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)

这篇关于Django模型:保存模型后,为每个标识符生成序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆