[英]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循環並在實例字段中替換所需的鍵值。
example.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')
template.html
<form method="post" action="">
{% csrf_token %}
<button type="submit">Click Me!</button>
當我單擊СleckMe按鈕時,我獲得成功,但是數據庫中僅出現一個模型實例。 但是,基於這些數據,我希望出現四個:
"45-64": 0.016358024691358025,
"18-24": 0.37570950015055704,
"25-34": 0.2789897621198434,
"13-17": 0.2103470340258958,
"35-44": 0.11859567901234568
如果在get_ida_instance函數中用print(key +“:” +“” + str(value))替換用於創建實例的代碼,那么在控制台中,我會看到我需要的所有值。 為什么不創建其余實例?
您在內部循環中返回,因此它只能執行一次。 將返回語句移回兩個縮進級別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.