Django:非主键自动递增字段



有没有一种可能的方法可以创建一个像AutoField/BigAutoField一样不容易失败的non primary-key auto incremented field(重复的ID,…(?

我们创建AutoFieldNonPrimary并使用如下所示的自定义字段

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)

您可以使用post_save信号创建一个信号,如下所示:

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()

最新更新