Django扩展User字段,保存用户额外信息

发布于 2018-07-06  231 次阅读


class BaseModel(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)  # Field name made lowercase.
    createdatetime = models.DateTimeField(db_column='CreateDateTime',default=timezone.now)  # Field name made lowercase.
    modifydatetime = models.DateTimeField(db_column='ModifyDateTime',default=timezone.now)
    creator = models.IntegerField(db_column='Creator',blank=True, null=True)  # Field name made lowercase.
    modifier = models.IntegerField(db_column='Modifier',blank=True, null=True)  # Field name made lowercase.

    class Meta:
        abstract = True

class SysUserProfile(BaseModel):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    status = models.SmallIntegerField(db_column='Status',default=0)
    imagepath = models.CharField(db_column='ImagePath',max_length=256,blank=True,null=True)
    class Meta:
        db_table = 'Sys_UserProfile'
 
    def create_user_profile(sender, instance,created,**kwargs):
         if created:
            profile = SysUserProfile()
            profile.user = instance
            profile.save()
    #当创建User实体且保存时,会同时建立对应用户的SysUserProfile
    post_save.connect(create_user_profile, sender=User)

# 查询 __代表多表连接查询,查询的是User表的值
 object = SysUserProfile.objects.filter(user__id=id)\
 .values('status','user__email','user__first_name','user__last_name',\
 'user__id','user__last_login','user__username').first()

# 编辑
@csrf_exempt
def post_edit(request,kwargs):
    assert isinstance(request, HttpRequest)
    result = ResultModel()
    username = request.POST.get('UserName','')
    lastname = request.POST.get('LastName','')
    firstname = request.POST.get('FirstName','')
    email = request.POST.get('Email','')
    password = request.POST.get('Password','')
    status = request.POST.get('Status','')
    id = request.POST.get('Id','')
    user = User.objects.get(id=Id)
    if user is not None:
            user.last_name = lastname
            user.first_name = firstname
            user.set_password(password)
            user.save()
            #执行过user.save()时 对应的SysUserProfile对象已经建立
            user_profile = SysUserProfile.objects.get(user=user)
            user_profile.status = status
            user_profile.save()
            result.msg = '操作成功'
            result.flag = True
    else:
        result.msg = '用户Id不存在'
    return HttpResponse(json.dumps(result.tojson()), content_type="application/json")

LoneKing