SQLAlchemy 无疑是非常强大的,但是文档隐含地假设了很多先验知识和关系主题,混合了 backref 和新的首选 back_populates() 方法,我觉得这很困惑。
以下模型设计几乎与处理 Association Objects for many-to-many relationships 的文档中的指南完全相同。 .可以看到评论还是和原文一样的,只是改了代码而已。
class MatchTeams(db.Model):
match_id = db.Column(db.String, db.ForeignKey('match.id'), primary_key=True)
team_id = db.Column(db.String, db.ForeignKey('team.id'), primary_key=True)
team_score = db.Column(db.Integer, nullable="True")
# bidirectional attribute/collection of "user"/"user_keywords"
match = db.relationship("Match",
backref=db.backref("match_teams",
cascade="all, delete-orphan")
)
# reference to the "Keyword" object
team = db.relationship("Team")
class Match(db.Model):
id = db.Column(db.String, primary_key=True)
# Many side of many to one with Round
round_id = db.Column(db.Integer, ForeignKey('round.id'))
round = db.relationship("Round", back_populates="matches")
# Start of M2M
# association proxy of "match_teams" collection
# to "team" attribute
teams = association_proxy('match_teams', 'team')
def __repr__(self):
return '<Match: %r>' % (self.id)
class Team(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
goals_for = db.Column(db.Integer)
goals_against = db.Column(db.Integer)
wins = db.Column(db.Integer)
losses = db.Column(db.Integer)
points = db.Column(db.Integer)
matches_played = db.Column(db.Integer)
def __repr__(self):
return '<Team %r with ID: %r>' % (self.name, self.id)
但是这个应该将团队实例 find_liverpool 与匹配实例 find_match (两个样板对象)相关联的代码段不起作用:
find_liverpool = Team.query.filter(Team.id==1).first()
print(find_liverpool)
find_match = Match.query.filter(Match.id=="123").first()
print(find_match)
find_match.teams.append(find_liverpool)
并输出以下内容:
Traceback (most recent call last):
File "/REDACT/temp.py", line 12, in <module>
find_match.teams.append(find_liverpool)
File "/REDACT/lib/python3.4/site-packages/sqlalchemy/ext/associationproxy.py", line 609, in append
item = self._create(value)
File "/REDACT/lib/python3.4/site-packages/sqlalchemy/ext/associationproxy.py", line 532, in _create
return self.creator(value)
TypeError: __init__() takes 1 positional argument but 2 were given
<Team 'Liverpool' with ID: 1>
<Match: '123'>
最佳答案
调用append正在尝试 create a new instance MatchTeams,从文档中可以看出。这也在您链接到的“简化关联对象”下注明:
Where above, each
.keywords.append()operation is equivalent to:
>>> user.user_keywords.append(UserKeyword(Keyword('its_heavy')))
因此你的
find_match.teams.append(find_liverpool)
相当于
find_match.match_teams.append(MatchTeams(find_liverpool))
由于 MatchTeams 没有明确定义的 __init__,它使用 _default_constructor()作为constructor (除非您已覆盖它),它只接受关键字参数以及 self,这是唯一的位置参数。
要解决此问题,请传递 creator工厂到您的关联代理:
class Match(db.Model):
teams = association_proxy('match_teams', 'team',
creator=lambda team: MatchTeams(team=team))
或在 MatchTeams 上定义 __init__ 以满足您的需要,例如:
class MatchTeams(db.Model):
# Accepts as positional arguments as well
def __init__(self, team=None, match=None):
self.team = team
self.match = match
或显式创建关联对象:
db.session.add(MatchTeams(match=find_match, team=find_liverpool))
# etc.
关于python - SQLAlchemy:__init__() 采用 1 个位置参数,但给出了 2 个(多对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41222412/
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option
我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano
我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use
对于作为String#tr参数的单引号字符串文字中反斜杠的转义状态,我觉得有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用了'd',在双引号中转义时不会改变含义("\d"="d")。'\\'.tr('\\','x')#=>"x"'\\'.tr('\\d','x')#=>"\\"'\\'.tr('\\\d','x')#=>"x" 最佳答案 在tr中转义tr的第一个参数非常类似于正则表达式中的括号字符分组。您可以在表达式的开头使用^来否定匹配(替换任何不匹配的内容)并使用例如a-f来匹配一
我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些