有没有一种可能的方法来创建像AutoField/BigAutoField这样的non primary-key auto incremented field,而又不容易失败(重复的ids,...)?
发布于 2020-04-06 12:43:49
您可以使用信号创建一个,如下所示:
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-06 12:51:03
我们创建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)https://stackoverflow.com/questions/61053036
复制相似问题