is there a possible way to create a non primary-key auto incremented field
like a AutoField/BigAutoField
that is not prone to failure(duplicated ids, ...) ?
Asked
Active
Viewed 866 times
2 Answers
0
You can use the post_save
signal to create one, like this:
from django.db.models.signals import post_save
from django.dispatch import receiver
class YourModel(models.Model):
auto_field = models.BigIntegerField(null=True, default=None)
@receiver(post_save, sender=YourModel)
def update_auto_field(sender, instance, created, **kwargs):
if created:
instance.auto_field = instance.pk
instance.save()
-
1i'll try this in a minute – Django DO Apr 06 '20 at 04:49
-
1something is off with your signals, it keeps breaking, raise Error: `Fatal Python error: Cannot recover from stack overflow. ` – Django DO Apr 06 '20 at 05:15
0
We create AutoFieldNonPrimary
and use a custom field like below
from django.db.models.fields import AutoField
from django.db.models.fields import checks
class AutoFieldNonPrimary(AutoField):
def _check_primary_key(self):
if self.primary_key:
return [
checks.Error(
"AutoFieldNonPrimary must not set primary_key=True.",
obj=self,
id="fields.E100",
)
]
else:
return []
class YourModel(models.Model):
auto_field = models.AutoFieldNonPrimary(primary_key=False)

anjaneyulubatta505
- 10,713
- 1
- 52
- 62
-
it will raise an `AssertionError`, django only supports 1 `AutoField` at the moment (`id` is also an `AutoField`) – Django DO Apr 06 '20 at 05:03
-
@DjangoDO I didn't think. Can you give it a try ? I didn't test it. – anjaneyulubatta505 Apr 06 '20 at 08:20