Django: for loop and POST request create function



在项目中有一个模型,其中包含数据库中的现有实例。

class Instagram(models.Model):
userid = models.CharField(max_length=255, unique=True)
username = models.CharField(max_length=50, blank=True, null=True)

还有另一种型号,到目前为止没有安装装置

class InstagramAgesAnalitics(models.Model):    
instagram = models.ForeignKey(Instagram)
age = models.CharField(max_length=10)    
viewer_percentage = models.DecimalField(default=0, max_digits=5, decimal_places=2)

现在我需要从存储在json文件中的值中创建InstagramDemographicsAnalitics模型的新实例。为此,我编写了一个函数,该函数使用 for 循环并替换实例字段中所需的键值。

例子.json

{
"@nightcrvwlxr": {                              
"userId": "5697152",                
"content_persons_statistic": {
"ages": {
"45-64": 0.016358024691358025,
"18-24": 0.37570950015055704,
"25-34": 0.2789897621198434,
"13-17": 0.2103470340258958,
"35-44": 0.11859567901234568
},                      
"genders": {
"MALE": 0.6046939714680166,
"FEMALE": 0.39530602853198343
}
}           
}
}

views.py

from django.shortcuts import render
import json
from django.http import HttpResponse, HttpResponseRedirect
from .models import InstagramDemographicsAnalitics, Instagram, InstagramAgesAnalitics
def get_ida_instance(request):
with open('/home/jekson/projects/jsontest/example.json', encoding='utf-8') as f:
data = json.loads(f.read())
if request.method == 'POST':
for key, value in data.items():
print(value['userId'])
instagram = Instagram.objects.get(userid=value['userId'])
ages = (value["content_persons_statistic"]['ages'])
for key, value in ages.items():
ida = InstagramAgesAnalitics()
ida.instagram = instagram
ida.age_group = key
ida.viewer_percentage = float(str(value))
ida.save()
print(key + ":" + " " + str(value))
return HttpResponse("Succesful")
return render(request, 'ida.html')

模板.html

<form method="post" action="">
{% csrf_token %}
<button type="submit">Click Me!</button>

当我单击"Сleck Me"按钮时,我得到"成功",但数据库中只显示模型的一个实例。但我预计根据这些数据会出现四个:

"45-64": 0.016358024691358025,
"18-24": 0.37570950015055704,
"25-34": 0.2789897621198434,
"13-17": 0.2103470340258958,
"35-44": 0.11859567901234568

如果在get_ida_instance函数中将用于创建实例的代码替换为print(键 + ":" + " + str(值((,那么在控制台中我会看到我需要的所有值。为什么不创建其余实例?

你返回内部循环,所以它只能执行一次。将该返回语句向后移动两个缩进级别。

相关内容

最新更新