python - 如何将字典值分配给 user_id 以创建对象

标签 python

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'})

打印用户

displays [{'user_id': 1L}]

.. 如何在 Company_Type(user_id=user,type=c_type) 中将 1 分配给 user_id 以创建对象

最佳答案

如果user是一个长度为1的列表,包含一个dict,则可以按如下方式提取dict的值:

值 = user[0]['user_id']

您可以将代码修改为:

      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'})

此外,如果您需要确保 id 是整数,请将其转换为正确的数据类型,如 int(id)

关于python - 如何将字典值分配给 user_id 以创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34286916/

相关文章:

python - 为什么 tempfile 似乎在 with 语句中删除了自身?

python - 在引发的异常中执行自定义代码

python - 为什么这个脚本在 python3 中比在 python2 中花费更多的时间?

python - 导入错误 : No module named bz2 for Python 2. 7.2

Python/Tweepy 转发以下 Twitter 帐户

python - 为什么我不能在 Python 中将 uint16 数组分配给数组向量?

python - Pandas :用第二列中出现次数之间的 obs 计数填充一列

python - 如何从 python pandas 中的 json 文件中提取非嵌套列?

python - 如何将由各种ASCII码组成的int值转换为其对应的字符串?

python - 如何使用 Tensorflow 中的 Hugging Face Transformers 库对自定义数据进行文本分类?