2013-03-29 55 views
1

當我打電話User.create_user,我得到以下錯誤:Django會不會讓我再去救一個User對象

IntegrityError at /login 
users_user.status_id may not be NULL 

注:我已經看過了一堆上的其他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

回答

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 
+0

完美!這工作像一個魅力。我對這個項目還有另外一個問題,既然你對這個知識很瞭解,我想知道你是否也可以幫助我?它在 http://stackoverflow.com/questions/15712582/my-status-object-is-not-saving-in-django 謝謝! – Abs

相關問題