我是 python 的新手。我有两个 SQLAlchemy 模型如下:
class listing(db.Model):
id = db.Integer(primary_key=True)
title = db.String()
location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
location = db.relationship('Location', lazy='joined')
class location(db.Model):
id = db.Integer(primary_key=True)
title = db.String()
我有两个 Marshmallow 模式类:
class ListingSchema(Schema):
id = fields.Int()
title = fields.Str()
location_id = fields.Int()
class LocationSchema(Schema):
id = fields.Int()
title = fields.Str()
我创建了一个嵌套的模式类:
class NestedSchema(Schema):
listing = fields.Nested(ListingSchema)
location fields.Nested(LocationSchema)
我正在做这样的连接查询:
listing,location = db.session.query(Listing,Location)\
.join(Location, and_(Listing.location_id == Location.id))\
.filter(Listing.id == listing_id).first()
数据加载到我检查过的对象中。如何解析这个模式? 我试过了
result,errors = nested_listing_Schema(listing,location)
这给出错误:“列表对象不可迭代。”
最佳答案
正确的是使用你创建的类 NestedSchema 而不是 nested_schema,这样做:
result,errors = NestedSchema().dump({'listing':listing,'location':location})
结果将是:
dict: {
u'listing': {u'id': 8, u'title': u'foo'},
u'location': {u'id': 30, u'title': u'bar'}
}
但我不明白你为什么要制作一个“NestedSchema”,我想你可以用另一种方式来做。
首先,忘记类“NestedSchema”。
之后,更改您的“ListingSchema”,如下所示:
class ListingSchema(Schema):
id = fields.Int()
title = fields.Str()
location_id = fields.Int()
location = fields.Nested("LocationSchema") #The diff is here
现在您可以:
listing = db.session.query(Listing).get(listing_id) # Suppose listing_id = 8
result,errors = ListingSchema().dump(listing)
print result
结果将是:
dict: {
u'id': 8, u'title': u'foo', u'location_id': 30, u'location': {u'id': 30, u'title': u'bar'}
}
请注意,现在“位置”是“列表”的属性。
而且你仍然可以制作 Two-Way Nesting , 只需在 Listing (model) 中添加一个 backref 并添加嵌套在 LocationSchema 中的 ListingSchema
class Listing(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(45), nullable=False)
location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
location = db.relationship('Location', lazy='joined', backref="listings") #the diff is here
class LocationSchema(Schema):
id = fields.Int()
title = fields.Str()
listings = fields.Nested("ListingSchema", many=True, exclude=("location",)) #The property name is the same as in bakcref
many=True 是因为我们有一个一对多的关系。
exclude=("location")是为了避免递归异常。
现在我们也可以按位置搜索了。
location = db.session.query(Location).get(location_id) # Suppose location_id = 30
result,errors = LocationSchema().dump(location)
print result
dict: {u'id': 30, u'title': u'bar',
u'listings': [
{u'location_id': 30, u'id': 8, u'title': u'foo'},
{u'location_id': 30, u'id': 9, u'title': u'foo bar baz'},
...
]
}
您可以查看有关它的文档here
关于python - 用棉花糖序列化两个嵌套模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39318251/
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc
我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的
我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是