Django duplicate primary keys

Viewed 377

I have a form that creates an object with the same previous id after submission. How do I change the uuid to be random each time?

class TbTerminalPermission(models.Model):
    id = models.CharField(
        primary_key=True, default=str(uuid.uuid4()).replace('-', ''), max_length=60)
    terminal = models.ForeignKey(
        'app.TbTerminal', on_delete=models.CASCADE, db_column='ter_id')
    user = models.ForeignKey(
        TbUser, on_delete=models.CASCADE, db_column='user_id')

    class Meta:
        managed = False
        db_table = 'tb_terminal_permission'
        unique_together = ('id', 'terminal', 'user')
class TbTerminalPermissionForm(forms.ModelForm):

    class Meta:
        model = TbTerminalPermission
        fields = ['user', 'terminal']

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = user
        if self.user:
            self.fields['user'].queryset = TbUser.objects.filter(
                id=self.user.id)
            self.fields['terminal'].queryset = TbTerminal.objects.exclude(
                tbterminalpermission__user=self.user).filter(customer=self.user.customer)

the error

Exception Value:    
(1062, "Duplicate entry 'ea870f29ec124e39aa5251b0862635f3' for key 'PRIMARY'")
2 Answers

If you work with:

id = models.CharField(
    primary_key=True,
    default=str(uuid.uuid4()).replace('-', ''),
    max_length=60
)

then Python will evaluate the str(uuid.uuid4()).replace('-', '') once, and use that as default each time it has to generate a primary key, hence if you save an object for the second time, there will be a collission.

You should define a function that generates strings, and pass a reference to that function as default, so:

def gen_pk_perm():
    return str(uuid.uuid4()).replace('-', '')

class TbTerminalPermission(models.Model):
    id = models.CharField(primary_key=True, default=gen_pk_perm, max_length=60)
    # …

This id replacement solved the issue

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

Related