Python SQLAlchemy TypeError:尝试用onetomany关系实例化模型时,类型为“dict”

2024-05-16 13:22:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用SQLAlchemy创建一个包含一对多关系的模型。一个食谱可能有许多与之相关的方向。然而,当我尝试实例化一个菜谱时,我得到了类型错误:unhable type:'dict'。如果我去掉方向的论点,一切都很好,它创建的食谱没有任何方向。我是否遗漏了一些不允许directions参数成为列表的内容

应用程序类型

data = {
  'cook_time': 15,
  'description': 'Recipe description',
  'directions': [{'order': 1, 'text': 'First direction'},
                 {'order': 2, 'text': 'Second direction'}],
  'image_url': 'https://via.placeholder.com/800x300?text=Recipe+Image',
  'name': 'Test recipe 2',
  'prep_time': 15,
  'servings': 6
}

recipe = models.Recipe(
  name=data['name'],
  description=data['description'],
  image_url=data['image_url'],
  prep_time=data['prep_time'],
  cook_time=data['cook_time'],
  servings=data['servings'],
  directions=data['directions']
)

型号.py

class Recipe(db.Model):
   __tablename__ = 'recipes'

   id = db.Column(db.Integer, primary_key=True)
   name = db.Column(db.String(200), index=True)
   description = db.Column(db.String(2000))
   image_url = db.Column(db.String(200))
   prep_time = db.Column(db.Integer)
   cook_time = db.Column(db.Integer)
   servings = db.Column(db.Integer)

   directions = db.relationship('RecipeDirection', backref='recipes', lazy='dynamic')


class RecipeDirection(db.Model):
   __tablename__ = 'recipe_directions'

   id = db.Column(db.Integer, primary_key=True)
   recipe_id = db.Column(db.Integer, db.ForeignKey('recipes.id'))
   order = db.Column(db.Integer)
   text = db.Column(db.String(1000))

Tags: textnameimageurldbdatatimerecipe
1条回答
网友
1楼 · 发布于 2024-05-16 13:22:58

出现错误是因为SQLAlchemy希望方向是RecipeDirection的列表。要解决这个问题,首先创建一个RecipeDirection列表


data = {
  'cook_time': 15,
  'description': 'Recipe description',
  'directions': [{'order': 1, 'text': 'First direction'},
                 {'order': 2, 'text': 'Second direction'}],
  'image_url': 'https://via.placeholder.com/800x300?text=Recipe+Image',
  'name': 'Test recipe 2',
  'prep_time': 15,
  'servings': 6
}

# Create a list of `RecipeDirection`
directions = []
for direction in data.get("directions", []):
    directions.append(models.RecipeDirection(**direction))

recipe = models.Recipe(
  name=data['name'],
  description=data['description'],
  image_url=data['image_url'],
  prep_time=data['prep_time'],
  cook_time=data['cook_time'],
  servings=data['servings'],
  directions=directions  # Now list of RecipieDirection not list of dicts
)

我还建议研究一个serilizer,它将为您处理编组和序列化嵌套数据结构的一些细节,例如marshmallow-sqlalchemy

相关问题 更多 >