Flask / SQLAlchemy错误:TypeError:不兼容的集合类型:unicode不是类似列表的

时间:2015-03-30 10:21:44

标签: flask sqlalchemy

我在sqlalchemy中的多对多关系中插入数据时遇到此错误。 Models.py

class Event(db.Model):
__tablename__ = 'event'
id = db.Column(db.String(255), primary_key=True)
title = db.Column(db.String(255))
image_url = db.Column(db.String(255))
category_id = db.Column(db.String(255), db.ForeignKey('category.id'),
                        nullable=True)
subheading = db.Column(db.String(255))
event_city = db.Column(db.String(255))
venue = db.Column(db.String(255))
start_date = db.Column(db.DateTime)
end_date = db.Column(db.DateTime)
description = db.Column(db.String(255))
speaker = db.relationship("Speaker",
                          secondary=association_table)
errors = {}

def __init(self, **kwargs):
    print kwargs
    speaker1 = db.session.query(Speaker).first()
    print speaker
    self.speaker.append(speaker1)
    self.id = generate_id()
    kwargs.pop(EVENT_FIELDS['EVENT_SPEAKER'])
    kwargs.pop(EVENT_FIELDS['EVENT_CATEGORY'])
    for key, value in kwargs.iteritems():
        try:
            setattr(self, key, value)
        except ex:
            Event.errors = FORM_EMPTY_FIELD.format(key)

关联表是

association_table = db.Table('association',
                         db.Column('speaker_id', db.String(255),
                                   db.ForeignKey('speaker.id')),
                         db.Column('event_id', db.String(255),
                                   db.ForeignKey('event.id')))

当我插入数据时,我收到错误,如上所述

1 个答案:

答案 0 :(得分:0)

在M2M关系中,模型事件的扬声器列中的关联必须以这种方式作为列表(括号[]之间的方式)传递,请在__init__方法中注明说话者的分配:

def __init(self, **kwargs):
    print kwargs
    speaker1 = db.session.query(Speaker).first()
    print speaker
    self.speaker = [speaker1]
    self.id = generate_id()
    kwargs.pop(EVENT_FIELDS['EVENT_SPEAKER'])
    kwargs.pop(EVENT_FIELDS['EVENT_CATEGORY'])
    for key, value in kwargs.iteritems():
        try:
            setattr(self, key, value)
        except ex:
            Event.errors = FORM_EMPTY_FIELD.format(key)