Django IntegrityError:(1048,“Column'user_id'不能为null”)

时间:2013-08-28 05:57:38

标签: mysql django

这是我的models.py

class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
class Meta:
    db_table = 'CfitUser'
def __str__(self):  
      return "%s's profile" % self.user  

@receiver(post_save, sender=User)
def create_cfituser(sender, instance, created, **kwargs):  
    if created:  
        Cfituser.objects.get_or_create(user=instance) 

这是我的views.py

@api_view(['GET', 'POST'])
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
    cfituser = Cfituser.objects.all()
    serializer = CfituserSerializer(cfituser, many=True)
    return Response(serializer.data)

elif request.method == 'POST':
    serializer = CfituserSerializer(data=request.DATA)
    if serializer.is_valid():
            print serializer.data
            user = User.objects.create_user(username = serializer.data['socialid'])
            cfituser = Cfituser.objects.get(user = user)
            cfituser.accesstoken = serializer.data['accesstoken']
            cfituser.socialid = serializer.data['socialid']
            cfituser.save()
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

每当有HTTP Post请求时,我的数据库表都按预期填充,但此错误不断弹出。我已经尝试了几乎所有可用的解决方案,但我坚持这一点。

我尝试了user = models.OneToOneField(User, null = True),但这导致我的数据库表中有两个条目,一个带有user_id = NULL,另一个带有user_id = actualvalue

有关如何解决此问题的任何建议吗?

2 个答案:

答案 0 :(得分:1)

默认情况下保存将条目提交到数据库,以防止这种情况发生,将commit=False传递给save(),然后进行自定义。

 serializer = serializer.save(commit=False)

 user, created = User.objects.get_or_create(username = serializer.socialid) 
 cfituser, created = Cfituser.objects.get_or_create(user = user)
 # cfituser.user = user This line is unnecessary
 cfituser.accesstoken = serializer.accesstoken
 cfituser.socialid = serializer.socialid

 cfituser.save()
 serializer.save()

您也在重复工作,因为您的信号也会尝试创建用户。如果您使用的是django 1.5,请使用customized user model;对于社会注册/ oauth,请使用django-social-auth

答案 1 :(得分:0)

OneToOneField表示,在Cfituser.user中,关系的反面将直接返回单个对象(user.cfituser给出Cfituser)。 SO Cfituser.user必须在表格中唯一(唯一的)。

class Cfituser(models.Model):
    user = models.OneToOneField(User)
    socialid = models.IntegerField(null=True)
    accesstoken = models.CharField(max_length=255L, null = True)
    def __unicode__(self):  
         return "%s's profile" % self.user.username  


def users_create(request, format = None):
"""
List all users, or create a new user.
"""
    if request.method == 'GET':
        cfituser = Cfituser.objects.all()
        serializer = CfituserSerializer(cfituser, many=True)
        return Response(serializer.data) 
    elif request.method == 'POST':
        serializer = CfituserSerializer(data=request.DATA)
        if serializer.is_valid():
            print serializer.data
            user = User.objects.create_user(username = serializer.data['socialid'])                
            Cfituser(user = user,accesstoken = serializer.data['accesstoken'],socialid = serializer.data['socialid']).save()
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)