[Answer]-Unique value issue

1👍

Error in your code: you don’t check if this model was saved before. Test case:

vehicle = models.Vehicle(name='Foo')
vehicle.save() #variant==0 by default
Vehicle.active = False
vehicle.save() #there is already a record with this name. Increment variant anyway

This approach looks better for me:

def save(self, *args, **kwargs):
    if self.id is None: #works only when saved first time
        self.variant = Vehicle.objects.filter(name=self.name).count()
    super(Vehicle, self).save(*args, **kwargs)
👤Marat

Leave a comment