[英]AttributeError: 'str' object has no attribute 'get_name'?
[英]meal, created = Meal.objects.get_or_create(name=meal_data.get('name', '')) AttributeError: 'str' object has no attribute 'get'
這是 django rest_framework api 我為餐廳創建了這個 api。 這是菜單 api。我想將 menu.json 的數據保存到我的數據庫中,但我不能。 你能給我任何建議來將 json 數據保存到我的模型中嗎? 我收到此錯誤:
File "C:\Users\OSMAN MERT\Desktop\menu\menu_core\api\models.py", line 36, in store_json_data
meal, created = Meal.objects.get_or_create(name=meal_data.get('name', ''))
AttributeError: 'str' object has no attribute 'get'
我該如何解決? 我需要你的幫助?
模型.py
from django.db import models
import json
# Create your models here.
class Meal(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
is_vegetarian = models.BooleanField(default=False)
is_vegan = models.BooleanField(default=False)
class Ingredient(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
groups = models.CharField(max_length=100)
class Option(models.Model):
id = models.AutoField(primary_key=True)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
quality = models.CharField(max_length=100)
price = models.FloatField()
per_amount = models.CharField(max_length=100)
class MealIngredient(models.Model):
id = models.AutoField(primary_key=True)
meal = models.ForeignKey(Meal, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
path = r"C:\Users\OSMAN MERT\Desktop\menu\menu_core\menu.json"
def store_json_data(json_data):
for meal_data in json_data:
meal, created = Meal.objects.get_or_create(name=meal_data.get('name', ''))
if not created:
meal.is_vegetarian = meal_data.get('is_vegetarian', False)
meal.is_vegan = meal_data.get('is_vegan', False)
meal.save()
for ingredient_data in meal_data.get('ingredients', []):
ingredient, _ = Ingredient.objects.get_or_create(name=ingredient_data.get('name', ''), meal=meal)
for option_data in ingredient_data.get('options', []):
option, _ = Option.objects.get_or_create(quality=option_data.get('quality', ''), ingredient=ingredient)
option.price = option_data.get('price', 0)
option.save()
def load_json_file(path):
with open(path) as json_file:
json_data = json.load(json_file)
store_json_data(json_data)
load_json_file(path)
這是來自 menu.json 的一些數據,並非所有代碼都包含在那里。 菜單.json
{
"meals": [
{
"id": 1,
"name": "Rice and chicken bowl",
"ingredients": [
{ "name": "Rice", "quantity": 120, "quantity_type": "gram" },
{ "name": "Chicken", "quantity": 85, "quantity_type": "gram" }
]
},
{
"id": 2,
"name": "Pasta with marinara sauce and vegetables",
"ingredients": [
{ "name": "Pasta", "quantity": 115, "quantity_type": "gram" },
{
"name": "Marinara sauce",
"quantity": 120,
"quantity_type": "millilitre"
},
{ "name": "Vegetables", "quantity": 240, "quantity_type": "gram" }
]
},
{
"id": 3,
"name": "Grilled chicken with roasted vegetables",
"ingredients": [
{ "name": "Chicken", "quantity": 85, "quantity_type": "gram" },
{ "name": "Vegetables", "quantity": 240, "quantity_type": "gram" }
]
},
{
"id": 4,
"name": "Beef stir-fry with rice",
"ingredients": [
{ "name": "Beef", "quantity": 115, "quantity_type": "gram" },
{ "name": "Rice", "quantity": 120, "quantity_type": "gram" },
{ "name": "Vegetables", "quantity": 240, "quantity_type": "gram" }
]
},
{
"id": 5,
"name": "Pork chops with mashed potatoes and gravy",
"ingredients": [
{ "name": "Pork chops", "quantity": 115, "quantity_type": "gram" },
{
"name": "Mashed potatoes",
"quantity": 120,
"quantity_type": "gram"
},
{ "name": "Gravy", "quantity": 120, "quantity_type": "millilitre" }
]
},
{
"id": 6,
"name": "Grilled salmon with roasted asparagus",
"ingredients": [
{ "name": "Salmon", "quantity": 85, "quantity_type": "gram" },
{ "name": "Asparagus", "quantity": 240, "quantity_type": "gram" }
]
},
{
"id": 7,
"name": "Shrimp scampi with linguine",
"ingredients": [
{ "name": "Shrimp", "quantity": 115, "quantity_type": "gram" },
{ "name": "Linguine", "quantity": 115, "quantity_type": "gram" },
{ "name": "Butter", "quantity": 10, "quantity_type": "millilitre" },
{ "name": "Garlic", "quantity": 10, "quantity_type": "gram" },
{ "name": "White wine", "quantity": 60, "quantity_type": "millilitre" }
]
},
{
"id": 8,
"name": "Vegetarian stir-fry with tofu",
"ingredients": [
{ "name": "Tofu", "quantity": 115, "quantity_type": "gram" },
{ "name": "Rice", "quantity": 120, "quantity_type": "gram" },
{ "name": "Vegetables", "quantity": 240, "quantity_type": "gram" }
]
},
{
"id": 9,
"name": "Fruit salad with mixed berries and yogurt",
"ingredients": [
{ "name": "Mixed berries", "quantity": 240, "quantity_type": "gram" },
{ "name": "Yogurt", "quantity": 120, "quantity_type": "millilitre" }
]
}
],
"ingredients": [
{
"name": "Rice",
"groups": ["vegan", "vegetarian"],
"options": [
{
"name": "Long grain white rice",
"quality": "high",
"price": 3,
"per_amount": "kilogram"
},
{
"name": "Medium grain brown rice",
"quality": "medium",
"price": 2,
"per_amount": "kilogram"
},
{
"name": "Quick cooking white rice",
"quality": "low",
"price": 1.5,
"per_amount": "kilogram"
}
]
}
首先,你的menu.json
你上傳的格式不對。 缺少一些字符。
假設你有正確的 json 就像你上傳到變量json_data
你顯示的錯誤意味着你得到的meal_data
是字符串。 而且它不能使用屬性get
。
嘗試像這樣更新以正確獲取 json 中的每頓飯meal_data
變成 dict 並且可以使用get
for meal_data in json_data.get("meals"):
meal, created = Meal.objects.get_or_create(name=meal_data.get('name', ''))
最主要的是你沒有在字典中正確循環(你試圖訪問key
內的name
屬性,它是一個字符串)。 您可以:
def store_json_data(json_data):
for key, meal_data in json_data.items():
if key == 'meals':
for meal in meal_data:
print(meal.get('name', ''))
if key == 'ingredients':
for ingredient in meal_data:
...
或者,不是遍歷字典key:value pair
,而是手動訪問列表值,然后遍歷它:
def store_json_data(json_data):
meals = json_data.get("meals")
ingredients = json_data["ingredients"]
for meal in meals:
print(meal.get('name', ''))
for ingredient in ingredients:
...
話雖如此,您嘗試執行的操作將行不通,因為當您第一次進行遷移時,數據庫表尚未創建並將引發OperationalError
。
我建議使用post_migrate信號來填充您的表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.