1

当我打电话时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

4

1 回答 1

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)

 

然后你注意到你可能已经使用了 builtin 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
于 2013-03-29T22:12:12.237 回答