Python 如何为JSONField创建一个django模型,该模型从同一个表中的其他字段获取值?
我正在用django编写一个模型,如下所示:Python 如何为JSONField创建一个django模型,该模型从同一个表中的其他字段获取值?,python,mysql,django,Python,Mysql,Django,我正在用django编写一个模型,如下所示: name = models.CharField(max_length=50) address = models.CharField(max_length=100) info = JSONField() 问题: 对于POST请求,我将提供名称和地址作为json。现在,我应该如何在各自的字段中存储名称和地址,以及如何存储json数据,即“名称:{…},地址:{…}”,并将其存储到信息字段中?这或多或少是我创建post请求的方式: class MyPos
name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
info = JSONField()
问题:
对于POST请求,我将提供名称和地址作为json。现在,我应该如何在各自的字段中存储名称和地址,以及如何存储json数据,即“名称:{…},地址:{…}”,并将其存储到信息字段中?这或多或少是我创建post请求的方式:
class MyPostView(View):
def post(self, request):
# Get request data
data = json.loads(request.body)
# Extract the values I need
name = data.get('name')
address = data.get('address')
# If the info already comes from the request do this
info = data.get('info')
# If you want to create the info field here do this
info = {'name':name, 'address': address}
# Create new model object
new_profile = Profile()
# Assign values
new_profile.name = name
new_profile.address = address
new_profile.info = info
# Save my object to database
new_profile.save()
# Return response (change this to whatever you want to return)
return HttpResponse("Success")
在这里,我使用基于类的视图,但您也可以以同样的方式使用基于函数的视图。
我只是不知道你为什么要把姓名和地址的信息保存两次
我希望有帮助 这或多或少是我创建post请求的方式:
class MyPostView(View):
def post(self, request):
# Get request data
data = json.loads(request.body)
# Extract the values I need
name = data.get('name')
address = data.get('address')
# If the info already comes from the request do this
info = data.get('info')
# If you want to create the info field here do this
info = {'name':name, 'address': address}
# Create new model object
new_profile = Profile()
# Assign values
new_profile.name = name
new_profile.address = address
new_profile.info = info
# Save my object to database
new_profile.save()
# Return response (change this to whatever you want to return)
return HttpResponse("Success")
在这里,我使用基于类的视图,但您也可以以同样的方式使用基于函数的视图。
我只是不知道你为什么要把姓名和地址的信息保存两次
我希望有帮助 您可以重写save方法,该方法将在保存实例之前将这些字段添加到info JSONField中 见:
无论如何,我建议您不要这样做,因为您正在同一个表的列中创建冗余。您可以重写save方法,该方法将在保存实例之前将这些字段添加到info JSONField中 见: 无论如何,我建议您不要这样做,因为您正在同一个表的列中创建冗余