简体   繁体   English

如何将dict值分配给user_id以创建对象

[英]How to assign dict values to user_id for creating objects

def insertCompany_type(request):
          if request.method == 'POST':
             try:
                data = json.loads(request.body)
                c_type = data["subject"]
                user = get_user_id(request)
                print user
                c_ty=Company_Type(user_id=user,type=c_type)
                c_ty.save(force_insert=True)
             except:
                     print 'nope'
          return JsonResponse({'status': 'success'})

print user

displays [{'user_id': 1L}] 显示[{'user_id':1L}]

.. How can i assign 1 to user_id in Company_Type(user_id=user,type=c_type) for creating objects ..我怎样才能分配1至user_idCompany_Type(user_id=user,type=c_type)用于创建对象

When you actually make a user (which doesnt happen your snippet of code) you can pass a constuctor argument setting user_id. 当您真正成为一个用户时(这不会发生您的代码片段),您可以传递一个构造函数参数设置user_id。 eg 例如

myUser = User(name="shalin", user_id=1)
myUser.save()

Also, you can get user objects from requests simply by doing this: 此外,您只需执行以下操作即可从请求中获取用户对象:

user = request.user

which is a bit easier than what you're doing I think. 这比我想的要容易一些。

If user is a list of length 1, containing a dict, you can extract the value of a dict as follows: 如果user是长度为1的列表,其中包含字典,则可以按以下方式提取字典的值:

value = user[0]['user_id']

You could modify your code as: 您可以将代码修改为:

      if request.method == 'POST':
         try:
            data = json.loads(request.body)
            c_type = data["subject"]
            user = get_user_id(request)
            id = user[0]['user_id']
            c_ty=Company_Type(user_id=id,type=c_type)
            c_ty.save(force_insert=True)
         except:
                 print 'nope'
      return JsonResponse({'status': 'success'})

Also if you need to make sure the id is an integer cast it to the right data type as int(id) 另外,如果您需要确保id为整数,则将其强制转换为正确的数据类型,如int(id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM