我很擅长同时使用SQLALCHEMY
和PYRAMID
网络框架。我正在努力解决一些可能是一个简单的修复,但我还没有能够弄明白。我查看了一些posts here on Stacks,但他们并没有完全回答我的问题。
我的many-to-many
表中有database
个关系。我正在尝试return
来自父表categories
的对象(assessment
)。我现在正在尝试:return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link}
但这不起作用 - > 'categories': assessment.categories.assessment_category_link
我能够返回除类别之外的所有对象。以下是相关的错误和代码。
TRACEBACK:
line 306, in get_assessment
return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link}
AttributeError: 'InstrumentedList' object has no attribute 'assessment_category_link'
SQLALCHEMY TABLE / RELATIONSHIP:
# MANY-to-MANY
association_table = Table('assessment_category_link', Base.metadata,
Column('assessment_id', Integer, ForeignKey('assessments.assessment_id')),
Column('category_id', Integer, ForeignKey('categories.category_id')))
class Assessment(Base):
# column/entity code
categories = relationship('Category', secondary='assessment_category_link', backref='assessments')
def __init__(self, name, text, user, video, categories):
# CODE
self.categories = categories
GET()方法,特别是抛出错误的return
值:
@view_config(route_name='assessment', request_method='GET', renderer='json')
def get_assessment(request):
with transaction.manager:
assessment_id = int(request.matchdict['id'])
assessment = api.retrieve_assessment(assessment_id)
if not assessment:
raise HTTPNotFound()
return {'name': assessment.name, 'text': assessment.text, 'user': assessment.user_id, 'video':assessment.video_id, 'categories': assessment.categories.assessment_category_link}
答案 0 :(得分:1)
我不确定您要实现的目标,因为assessment.categories
会返回您需要迭代的Category
个对象列表。这样的列表没有一个名为assessment_category_link
的属性(正如异常告诉你的那样)是合乎逻辑的,并且我不清楚为什么你想要访问关联对象呢!
与secondary
关键字参数的关系意味着隐藏此复杂性,以便assessment.categories
透明地返回您所追求的列表。
您可以根据需要表示类别列表,这是针对您的案例的建议:
{...., 'categories': ', '.join([str(i) for i in assessment.categories])}
答案 1 :(得分:1)
上面的答案非常接近,但工作code
是:
{...., 'categories': ','.join([str(i) for i in assessment.categories])}
正如类似的堆栈问题/答案对同一问题的建议:TypeError: sequence item 0: expected string, int found