首页 \ 问答 \ 为什么SQLAlchemy中的ForeignKey和RelationshipProperty属性不会自动同步?(Why are not ForeignKey and RelationshipProperty attributes in SQLAlchemy automatically synchronized?)

为什么SQLAlchemy中的ForeignKey和RelationshipProperty属性不会自动同步?(Why are not ForeignKey and RelationshipProperty attributes in SQLAlchemy automatically synchronized?)

我试图弄清楚SQLAlchemy处理外键的方式。

考虑这些模型:

class ModelOne(Base):
   __tablename__ = 'model_one'

   id = Column(Integer, primary_key=True)
   ...

class ModelTwo(Base):
   __tablename__ = 'model_two'

   id = Column(Integer, primary_key=True)
   one_id = Column(Integer, ForeignKey('model_one.id'))
   one = relationship('ModelOne')

我假设如果我们有两个这样的模型,那么SQLAlchemy会发现ModelTwo.one_id和ModelTwo.one指的是同一个数据库列。

在创建ModelTwo记录时,我们可以使用ModelOne记录的数字ID或ModelOne实例来填充FK字段:

one = DBSession.query(ModelOne)....
two_a = ModelTwo(one_id=one.id)
two_b = ModelTwo(one=one)

这很有效。

但是这里有一个转折:在实例化ModelTwo实例后,根据我们初始化FK字段的方式,它的一个或另一个表示将保持未填充:

two_a.one is None # evaluates to True
two_b.one_id is None # evaluates to True

这是预期的行为吗? 如果是这样,这必须是开发人员头上的一个巨大的红旗。 当我们从DB检索记录作为声明性模型类的实例时,将填充record.one和record.one_id,但是当我们创建新记录时,情况并非如此!


I am trying to figure out the way SQLAlchemy is handling foreign keys.

Consider these models:

class ModelOne(Base):
   __tablename__ = 'model_one'

   id = Column(Integer, primary_key=True)
   ...

class ModelTwo(Base):
   __tablename__ = 'model_two'

   id = Column(Integer, primary_key=True)
   one_id = Column(Integer, ForeignKey('model_one.id'))
   one = relationship('ModelOne')

I assumed that if we have two models like this, then SQLAlchemy will figure out that ModelTwo.one_id and ModelTwo.one are referring to the same database column.

When creating ModelTwo records, we can use either numerical ID of the ModelOne records, or ModelOne instances to fill the FK field:

one = DBSession.query(ModelOne)....
two_a = ModelTwo(one_id=one.id)
two_b = ModelTwo(one=one)

This works.

But here's a twist: immediately after instantiating the ModelTwo instances, depending on how we initialize the FK field, one or the other representation of it will remain unpopulated:

two_a.one is None # evaluates to True
two_b.one_id is None # evaluates to True

Is this an expected behaviour? If so, this has to be a huge red flag in the head of a developer. When we retrieve a record from DB as an instance of a declarative model class, both record.one and record.one_id will be populated, but when we are creating a new record, that is not the case!


原文:https://stackoverflow.com/questions/24685814
更新时间:2022-04-26 08:04

最满意答案

include_once('simple_html_dom.php');
$html = new simple_html_dom();

$text = '<div id="content">
Hello World.
<div id="sub-content1">
Text I don\'t want to select.
</div>
<div id="sub-content2">
Text I don\'t want to select
</div>
</div>';

$html->load($text);
$selector =$html->find("div#content",0)->find("*");
foreach($selector  as $node){
$node->outertext = '';
}
$html->load($html->save()); 
$selector =$html->find("div#content",0);
echo $selector->innertext;

include_once('simple_html_dom.php');
$html = new simple_html_dom();

$text = '<div id="content">
Hello World.
<div id="sub-content1">
Text I don\'t want to select.
</div>
<div id="sub-content2">
Text I don\'t want to select
</div>
</div>';

$html->load($text);
$selector =$html->find("div#content",0)->find("*");
foreach($selector  as $node){
$node->outertext = '';
}
$html->load($html->save()); 
$selector =$html->find("div#content",0);
echo $selector->innertext;

相关问答

更多
  • 单独替换每个文本节点的内容,而不是一次更改整个文件的文本: loadHTMLFile('https://en.wikipedia.org/wiki/Banana'); // select all the text nodes $xpath = new DOMXPath($doc); $nodes = $xpath->query('//text()'); // replace t ...
  • 也许这会给你你想要的结果: foreach($info_html->find('div.info p') as $library) { $rating = $library->find('text', 1)->innertext; var_dump($rating); } Maybe this will give you the result you are looking for: foreach($info_html->find('div.info p') as $library) { ...
  • 你想尝试使用正则表达式吗? $subject = 'P BARCODE[pb]=21913000482538
    '; $pattern = '/P\sBARCODE\[pb\]=([0-9]*)
    /'; preg_match($pattern, $subject, $matches); print_r($matches); Would you like to try to use regexp? $subject = 'P BARCODE[pb]=21913000482538
    '; $ ...
  • 如果它总是在同一个地方你可以做: $html->find('.article text', 4); If it's always in the same place you can do: $html->find('.article text', 4);
  • include_once('simple_html_dom.php'); $html = new simple_html_dom(); $text = '
    Hello World.
    Text I don\'t want to select.
    Text I don\'t want to select
    '; $html->load($te ...
  • 在你的代码中 foreach($html->find('div[id=center].post') as $article) { ... } 应该 foreach($html->find('div#center .post') as $article) { ... } 输出: {“结果”:[{“date”:“Friday,01.03.2013。Year”,“text”:“\ u0161tita ra \ u010dunarskih and business systems”,“link”:“Defaul ...
  • 相关文章

    更多
  • sqlalchemy、storm和web2py dal的比较报告
  • 与synchronized有关的线程同步问题的一点非常规情况
  • 一步一步掌握线程机制(三)---synchronized和volatile的使用
  • \ 关于业务逻辑 我是否需要synchronized 方法 困惑?
  • elixir usage
  • jquery 怎么得到link中text的属性
  • 一步一步掌握线程机制(四)---同步方法和同步块
  • RelativeLayout代码中设置属性
  • XML中 属性与元素的用法
  • SOLR 中 Schema.xml 的filedType 的一些属性的理解
  • 最新问答

    更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)