当我致电User.create_user
时,我收到以下错误:
IntegrityError at /login
users_user.status_id may not be NULL
注意:我在SO上查看了一堆其他IntegrityError问题,但我无法解决这个问题。
我的模特看起来像这样:
class Status(models.Model):
status = models.CharField(max_length=200)
status_time = models.DateTimeField('date published')
def __init__(self, status = '', time=timezone.datetime.min, *args, **kwargs):
self.status = status
self.status_time = time
super(Status, self).__init__(*args, **kwargs)
def set_status(self, s):
self.status = s
self.status_time = timezone.datetime.now()
self.save()
def get_status(self):
now = timezone.datetime.now()
if now-self.status_time<datetime.timedelta(minutes=15):
return self.status
return None
class User(models.Model):
facebook_id = models.CharField(max_length=200)
friends = ListField()
status = models.OneToOneField(Status)
@classmethod
def create_user(cls, fid, friends):
k = User()
k.facebook_id = fid
k.friends = friends
k.save() #THE PROBLEM IS HERE
k.status = Status()
k.status.set_status('')
k.status.save()
k.save()
我还是不明白User.status_id代表什么。它为什么存在,为什么不能None
?
答案 0 :(得分:3)
您的问题是您以非创建状态保存用户。首先创建一个状态,然后您可以保存用户:
def create_user(cls, fid, friends):
k = User()
k.status = Status()
k.status.set_status('') # set_status saves the status
k.facebook_id = fid
k.friends = friends
k.save()
或者更好:
def create_user(cls, fid, friends):
status = Status()
status.set_status('')
User.objects.create(facebook_id=fid, friends=friends, status=status)
在惯用的django代码中,像create_user
这样的方法应该在模型管理器上:
class UserManager(models.Manager):
def create_user(self, fid, friends):
status = Status()
status.set_status('')
return self.create(facebook_id=fid, friends=friends, status=status)
class User(models.Model):
facebook_id = models.CharField(max_length=200)
friends = ListField()
status = models.OneToOneField(Status)
objects = UserManager()
然后你这样称呼它:
new_user = User.objects.create_user(fid, friends)
然后你注意到你可以只使用内置objects.create
,如果只有默认状态:
# A custom manager is no longer needed
class User(models.Model):
facebook_id = models.CharField(max_length=200)
friends = ListField()
status = models.OneToOneField(Status)
def save(self, *a, **kw):
# if this user doesn't have a status yet, create an empty one
if self.status is None:
self.status = Status()
self.status.set_status('')
super(User, self).save(*a, **kw)
# creating users:
new_user = User.objects.create(facebook_id=fid, friends=friends)
# status is set to an empty one automatically in save