【发布时间】:2020-08-30 03:27:01
【问题描述】:
更新
我无法弄清楚为什么我得到了错误的结果
但我一时兴起尝试了一些东西,它奏效了。虽然我不清楚为什么。
我添加了一个新的类方法来改变以下内容
发件人:
def is_added(self, topic)
收件人:
def isAdded(self,topic)
其余代码保持不变。
这是我现在在 shell 中看到的结果。
>>> h = Highlight(text="highlight2")
>>> t = Topic(title="topic2")
>>> db.session.add(h)
>>> db.session.add(t)
>>> h.topics.all()
[]
>>> h.AddToTopic(t)
>>> h.topics.all()
[<Topic 2>]
>>> h.is_added(t)
False
>>> h.isAdded(t)
True
>>>
我猜这与下划线在 python 中的特殊性有关?
但我现在可以继续前进了。
原帖
我在一个名为 Highlight 的模型中有以下方法:
# add highlight to topic
def AddToTopic(self, topic):
if not self.is_added(topic):
self.topics.append(topic)
# checks if a highlight is in a topic
def is_added(self, topic):
return self.topics.filter(
topic.id == highlights_topics.c.topic_id).count() > 0
当我使用以下场景加载 shell 上下文时:
>>> h = Highlight(text="highlight1")
>>> t = Topic(title="Topic 1")
>>> db.session.add_all([h,t])
>>> h.AddToTopic(t)
>>> h.topics.all()
结果:[<Topic 1>]
检查方法>>> h.is_added(t)我得到False
然后我尝试以下方法:
>>> x = h.topics.filter(t.id==highlights_topics.c.topic_id).count() > 0
>>> x
True
在 shell 上下文中,我只是手动创建了相同的函数。
为什么我看到了不同的结果?
此外,如果我在 shell 上下文中重新创建该函数,它就可以工作。
>>> def is_added(highlight, topic):
... return highlight.topics.filter(topic.id == highlights_topics.c.topic_id).count() > 0
...
>>> is_added(h, t)
True
>>>
【问题讨论】:
标签: python flask sqlalchemy