我用fbone启动了这个项目,并用它实现了一个名为DenormalizedText的Flask SQLAlchemy列扩展。我得到了这个概念和它的工作方式(不是我的问题),但是我的add
方法的实现有一些奇怪的结果。DenormalizedText
class DenormalizedText(Mutable, types.TypeDecorator):
"""
Stores denormalized primary keys that can be
accessed as a set.
:param coerce: coercion function that ensures correct
type is returned
:param separator: separator character
"""
impl = types.Text
def __init__(self, coerce=int, separator=" ", **kwargs):
self.coerce = coerce
self.separator = separator
super(DenormalizedText, self).__init__(**kwargs)
def process_bind_param(self, value, dialect):
if value is not None:
items = [str(item).strip() for item in value]
value = self.separator.join(item for item in items if item)
return value
def process_result_value(self, value, dialect):
if not value:
return set()
return set(self.coerce(item) for item in value.split(self.separator))
def copy_value(self, value):
return set(value)
我的类有一个名为
Person
的非规范化文本参数family
下面是add方法
# just adds each object to the other's family relationship
def add_family(self, person):
self.family.add(person.id)
person.family.add(self.id)
这里有一些奇怪的地方:
我对
family = Column(DenormalizedText)
有另一个关系,对另一个名为Person
的类做了完全相同的操作。这很管用。所以我想可能有一个自我引用实现的问题。但是fbone是用他们提供的Residence
类来实现的,这是有效的吗?!所以我写了一篇test。。。就这样过去了!
导致使用这种方法的一切都很好。两个
User
对象都在会话中并已提交,在尝试添加之前,我会再次检查“family member”(确保它们已保存到db并具有id)。偶尔我会遇到这样一个罕见的错误:
Person
就像我说的,这对
SAWarning: The IN-predicate on "persons.id" was invoked with an empty sequence. This results in a contradiction, which nonetheless can be expensive to evaluate. Consider alternative strategies for improved performance.
与residences
的关系很好,但这里是视图和表单处理程序中的相关代码,以防:def create_step2_family():
client = Person()
spouse = Person()
spouse_form = PersonalForm()
# default action
try:
client = Person.get_by_id(session['working_client'])
except KeyError:
flash('Please complete this section first.', 'warning')
return redirect(url_for('client.create_step1_personal'))
else:
# spouse form action
if request.method == 'POST' and spouse_form.validate_on_submit():
spouse_form.populate_obj(spouse)
spouse.type_code = SPOUSE
db.session.add(spouse)
db.session.commit()
if Person.get_by_id(spouse.id):
client.add_family(spouse)
db.session.add(client)
db.session.commit()
return render_template('clients/wizard/step2/family.html', active="Create",
client=client, spouse=spouse, spouse_form=spouse_form, active_tab="family")
最佳答案
我需要休假
错误“SAWarning: The IN-predicate on "persons.id" was invoked with an empty sequence. This results in a contradiction, which nonetheless can be expensive to evaluate. Consider alternative strategies for improved performance.
”是因为我正在对未返回任何内容的列调用查询,或者由于未添加任何内容,persons.id
的列表为空。
没有添加任何内容,因为我忘记了add方法底部的这几行:
def add_family(self, person):
self.family.add(person.id)
person.family.add(self.id)
self.family=set(self.family)
person.family=set(person.family)
我一团糟。无论如何,如果有人能对代码提供更好的解释或改进,我不会接受我的答案。
关于python - Flask-SQLAlchemy无法创建关系-SAWarning,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24231535/