我要怎么做才能将pk分配为默认值?这不起作用:
from django.db import models
class TeamMember(models.Model):
id = models.AutoField(primary_key=True)
order_listing = models.IntegerField(default=id)
答案 0 :(得分:1)
问题是直到将对象保存到数据库后才生成ID。但是,使用uuid可以解决此问题。
import uuid
from django.db import models
# unique id to be used as pk for TeamMember table.
unique_id = uuid.uuid4().hex
class TeamMember(models.Model):
id = models.CharField(primary_key=True,
default=unique_id, editable=False
)
order_listing = models.IntegerField(default=unique_id)
答案 1 :(得分:0)
如果想在每次保存对象时将order_listing
的值重置为id
,则可以使用以下内容。
from django.db import models
class TeamMember(models.Model):
id = models.AutoField(primary_key=True)
order_listing = models.IntegerField(null=True, blank=True)
def save(self, *args, **kw):
self.order_listing = self.id
return super(TeamMember, self).save(*args, **kw)
或下面的代码仅用于首次设置。
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import post_save
class TeamMember(models.Model):
id = models.AutoField(primary_key=True)
order_listing = models.IntegerField(null=True, blank=True)
@receiver(post_save, sender=TeamMember)
def order_listing_update(sender, instance, created, **kwargs):
if created:
instance.order_listing = instance.id
instance.save()