我正在尝试使用 SQLAlchemy 创建一个包含一对多关系的模型。一份食谱可能有许多与之相关的说明。然而,当我尝试实例化一个菜谱时,我得到TypeError: unhashable type: 'dict'。如果我删除方向参数,一切都会正常,并且它会创建没有任何方向的食谱。我是否遗漏了一些不允许方向参数成为列表的内容?
应用程序.py
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))
最佳答案
您收到错误是因为 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
)
我还建议研究一个序列化程序,它将为您处理编码和序列化嵌套数据结构的一些细节,例如 marshmallow-sqlalchemy
关于Python SQLAlchemy 类型错误 : unhashable type: 'dict' when trying to instantiate model with one-to-many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59474637/