kingofvir
V2EX  ›  Django

django orm

  •  
  •   kingofvir · Jan 24, 2019 · 3753 views
    This topic created in 2845 days ago, the information mentioned may be changed or developed.

    django orm 更新 model 某个字段为该 model 中某个外键 mode 字段的值。

    5 replies  •  2019-02-17 22:15:00 +08:00
    kingofvir
    kingofvir
    OP
    Jan 24, 2019
    1
    有 model A,model B,A.b = ForeignKey(B), 如优雅地设置 A.author = A.b.name.
    kingofvir
    kingofvir
    OP
    Jan 25, 2019
    2
    自顶
    mayorbryant
    mayorbryant
    Jan 25, 2019
    3
    难道 A.author = A.b.name 就不优雅了吗
    kingofvir
    kingofvir
    OP
    Jan 28, 2019
    4
    @mayorbryant 主要是为了数据更新,这样几万条数据更新需要执行几万个 sql
    banxi1988
    banxi1988
    Feb 17, 2019
    5
    根据我的理解给出一个使用纯 SQL 的解法,你可以自行翻译成 Django ORM 的写法
    针对如下表结构:

    ```sql
    CREATE TABLE `author` (
    `id` INTEGER,
    `name` TEXT,
    PRIMARY KEY(`id`)
    );


    CREATE TABLE `book` (
    `id` INTEGER,
    `name` TEXT NOT NULL,
    `author_id` INTEGER,
    `author_name` TEXT,
    PRIMARY KEY(`id`)
    );

    ````

    `book.author_name` 是后面加的,要填充其关联的 author 的名称可以使用如下 SQL 语句更新。

    ```sql
    update book set author_name = (select name from author where id = author_id)
    ```
    经过我使用 SQLite 测试是 OK 的。
    > Query executed successfully: update book set author_name = (select name from author where id = author_id) (took 0ms, 3 rows affected)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2549 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 05:29 · PVG 13:29 · LAX 21:29 · JFK 00:29
    ♥ Do have faith in what you're doing.