有没有一种可能的方法来创建一个不容易失败的non primary-key auto incremented field
like a (重复的ids,...)?AutoField/BigAutoField
问问题
356 次
2 回答
0
我们创建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)
于 2020-04-06T04:51:02.847 回答
0
您可以使用该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()
于 2020-04-06T04:43:48.507 回答