[Answered ]-Autoincrement field dependent for number of specific value appearances in django

1👍

Django doesn’t have a single specific tool to achieve your outcome. Here are two options.

1. Save() method
This is basically your approach. But it should be combined with Django’s UniqueConstraint.condition (docs) method to make sure the customer_number field is unique for each customer type. Model constraints can be set as a meta option.

class Customer(models.Model):
    customer_name = models.CharField(max_length=500)
    CUSTOMER_CHOICES = [
        ('pc', 'Private Customer'),
        ('bc', 'Business Customer'),
    ]
    customer_type = models.CharField(max_length=2, choices=CUSTOMER_CHOICES)

    class Meta:
        constraints = [
            models.UniqueConstrained(fields=['customer_number'], condition=Q(customer_type='pc'), name='unique_pc_customer'),
            models.UniqueConstrained(fields=['customer_number'], condition=Q(customer_type='bc'), name='unique_bc_customer'),
            ]

If the constraint is violated, an IntegrityError is raised. You can handle the error in your model save() method.

def save():
    try:
       #Set your customer_number
    except IntegrityError:
       #Handle the error as you wish

2. Separate models
You could define two additional models, one for pc one for bc. Those models would then be related to your Customer model one-to-one. The id of your pc model instance and bc model instance would be your customer number.

👤yagus

Leave a comment