1. <tfoot id='ejTiD'></tfoot>

    <small id='ejTiD'></small><noframes id='ejTiD'>

    • <bdo id='ejTiD'></bdo><ul id='ejTiD'></ul>
    <i id='ejTiD'><tr id='ejTiD'><dt id='ejTiD'><q id='ejTiD'><span id='ejTiD'><b id='ejTiD'><form id='ejTiD'><ins id='ejTiD'></ins><ul id='ejTiD'></ul><sub id='ejTiD'></sub></form><legend id='ejTiD'></legend><bdo id='ejTiD'><pre id='ejTiD'><center id='ejTiD'></center></pre></bdo></b><th id='ejTiD'></th></span></q></dt></tr></i><div id='ejTiD'><tfoot id='ejTiD'></tfoot><dl id='ejTiD'><fieldset id='ejTiD'></fieldset></dl></div>

      <legend id='ejTiD'><style id='ejTiD'><dir id='ejTiD'><q id='ejTiD'></q></dir></style></legend>
    1. 使用旧数据库在 django 项目中使用复合主键

      Working with composite primary key in django project with legacy database(使用旧数据库在 django 项目中使用复合主键)

        <small id='vo4cb'></small><noframes id='vo4cb'>

          <i id='vo4cb'><tr id='vo4cb'><dt id='vo4cb'><q id='vo4cb'><span id='vo4cb'><b id='vo4cb'><form id='vo4cb'><ins id='vo4cb'></ins><ul id='vo4cb'></ul><sub id='vo4cb'></sub></form><legend id='vo4cb'></legend><bdo id='vo4cb'><pre id='vo4cb'><center id='vo4cb'></center></pre></bdo></b><th id='vo4cb'></th></span></q></dt></tr></i><div id='vo4cb'><tfoot id='vo4cb'></tfoot><dl id='vo4cb'><fieldset id='vo4cb'></fieldset></dl></div>

            <tfoot id='vo4cb'></tfoot><legend id='vo4cb'><style id='vo4cb'><dir id='vo4cb'><q id='vo4cb'></q></dir></style></legend>
                <tbody id='vo4cb'></tbody>
              • <bdo id='vo4cb'></bdo><ul id='vo4cb'></ul>
              • 本文介绍了使用旧数据库在 django 项目中使用复合主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

                我有一个旧数据库,其中一些表包含复合主键.我通过运行 manage.py inspectdb 命令得到的模型如下所示.

                class MyTable(models.Model):field1_id = models.IntegerField(db_column='field1id', primary_key=True)is_favorite = models.BooleanField(db_column='isfavorite', default=False, null=False)is_admin = models.BooleanField(db_column='isadmin', default=False, null=False)role = models.IntegerField(默认=USER_GUEST,null=False)field2 = models.BooleanField(null=False, default=True)field3 = models.BooleanField(null=False, default=True)is_active = models.BooleanField(db_column='isactive', null=False, default=True)用户 = 模型.ForeignKey(自定义用户,models.DO_NOTHING,db_column='userid',primary_key=True)元类:管理 = 错误db_table = '我的表'unique_together = (('user', 'field1_id'),)

                我可以正常获取数据.但是,当我想在某个模型实例上运行 save() 命令时会出现问题.django 执行的查询不正确.例如:

                <预><代码>>>>从 web_services.apps.my_app.models 导入 MyTable>>>g = MyTable.objects.get(field1_id=12)>>>g.is_active = 真>>>g.save()>>>连接.查询[-1]{'time': '0.000', 'sql': 'UPDATE `mytable` SET `isfavorite` = 0,`isadmin` = 1,`role` = 3,`field2` = 1,`field3` = 1,`isactive` = 1 WHERE `mytable`.`field1id` = 12'}

                但我需要:

                {'time': '0.000', 'sql': 'UPDATE `mytable` SET `isfavorite` = 0, `isadmin` = 1, `role` = 3, `field2` = 1, `field3` = 1, `isactive` = 1 WHERE `mytable`.`field1id` = 12' AND `mytable`.`userid` = 1'}

                由于 django 不支持复合主键,那么克服该问题的最佳解决方案是什么?请注意,它是旧数据库表,没有 AutoField.

                添加旧表结构

                +------------+------------+------+-----+---------+-----+|领域 |类型 |空 |钥匙 |默认 |额外 |+------------+------------+------+-----+---------+-------+|用户名 |整数(11) |否 |PRI |空 |||field1id |整数(11) |否 |PRI |空 |||最喜欢 |整数(11) |否 ||0 |||isadmin |整数(11) |否 ||0 |||角色|整数(11) |是 ||空 |||场2 |tinyint(1) |否 ||1 |||字段3 |tinyint(1) |否 ||1 |||活跃 |tinyint(4) |否 ||1 ||+------------+------------+------+-----+---------+-------+

                解决方案

                不幸的是 django 没有 复合主键(复合主键也叫多列主键)

                有一个第三方库,不出所料地将其命名为 django-compositekey 这使得它成为可能创建一个具有多列主键的模型.但是,该项目并未得到维护,并且与最新版本的 django 不兼容.

                最好的办法是在表中添加一个新列,该列是一个 AutoField,并使其成为新的主键.目前构成主键的字段可以标记为 unique_together.虽然这对于一些查询来说可能并不理想.对大多数人来说已经足够了.

                如果您使用当前的表结构更新您的问题(如您的 sql 控制台中所示),我将更新我的答案以显示模型的外观.

                更新有很多不同的方法可以删除旧的复合主键并用新的自动增量主键替换它.这是最简单的,它只涉及 SQL

                CREATE TABLE newtable LIKE mytable;ALTER TABLE newtable DROP PRIMARY KEY;ALTER TABLE newtable ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY;将表 mytable 重命名为 mytable_old;将 TABLE newtable 重命名为 mytable;INSERT INTO mytable(userid,field1id, 其余字段)SELECT * FROM mytable_old;

                然后编辑您的模型并从这些字段中删除 primary_key=True 标志.

                脚注:
                某些数据库(例如 sqlite)不支持 CREATE TABLE 中的 LIKE 子句.在这些情况下,您必须查找原始表的 create table 语句,并在编辑表名后复制粘贴.从您的表结构来看,您似乎正在使用 mysql 并且它支持 LIKE 子句.

                I have a legacy database, where some table contains composite primary key. The model I get by running manage.py inspectdb command looks like this.

                class MyTable(models.Model):
                    field1_id = models.IntegerField(db_column='field1id', primary_key=True)
                    is_favorite = models.BooleanField(db_column='isfavorite', default=False, null=False)
                    is_admin = models.BooleanField(db_column='isadmin', default=False, null=False)
                    role = models.IntegerField(default=USER_GUEST, null=False)
                    field2 = models.BooleanField(null=False, default=True)
                    field3 = models.BooleanField(null=False, default=True)
                    is_active = models.BooleanField(db_column='isactive', null=False, default=True)
                
                    user = models.ForeignKey(
                        CustomUser, models.DO_NOTHING, db_column='userid', primary_key=True)
                
                    class Meta:
                        managed = False
                        db_table = 'mytable'
                        unique_together = (('user', 'field1_id'),)
                

                I can fetch data normally. However, the problem arises when I want to run save() command on some model instance. The query django executes is not correct one. For example:

                >>> from web_services.apps.my_app.models import MyTable
                >>> g = MyTable.objects.get(field1_id=12)
                >>> g.is_active = True
                >>> g.save()
                >>> connection.queries[-1]
                {'time': '0.000', 'sql': 'UPDATE `mytable` SET `isfavorite` = 0, `isadmin` = 1, `role` = 3, `field2` = 1, `field3` = 1, `isactive` = 1 WHERE `mytable`.`field1id` = 12'}
                

                But I need:

                {'time': '0.000', 'sql': 'UPDATE `mytable` SET `isfavorite` = 0, `isadmin` = 1, `role` = 3, `field2` = 1, `field3` = 1, `isactive` = 1 WHERE `mytable`.`field1id` = 12' AND `mytable`.`userid` = 1'}
                

                Since django does not support composite primary key, what would be the best solution to overcome that problem? Note, it's legacy database table and it didn't have AutoField.

                EDIT: adds legacy table structure

                +------------+------------+------+-----+---------+-------+
                | Field      | Type       | Null | Key | Default | Extra |
                +------------+------------+------+-----+---------+-------+
                | userid     | int(11)    | NO   | PRI | NULL    |       |
                | field1id   | int(11)    | NO   | PRI | NULL    |       |
                | isfavorite | int(11)    | NO   |     | 0       |       |
                | isadmin    | int(11)    | NO   |     | 0       |       |
                | role       | int(11)    | YES  |     | NULL    |       |
                | field2     | tinyint(1) | NO   |     | 1       |       |
                | field3     | tinyint(1) | NO   |     | 1       |       |
                | isactive   | tinyint(4) | NO   |     | 1       |       |
                +------------+------------+------+-----+---------+-------+
                

                解决方案

                Unfortunately django does not yet have a composite primary key (composite primary keys are also called multi column primary keys)

                There is a third party library, unsurprisingly name django-compositekey that makes it possible to create a model that has a multi column primary key. However that project is not maintained and not compatible with the latest versions of django.

                Your best bet, is to add a new column into your table which is a an AutoField and make it the new primary key. The fields that make up the primary key at present can then be marked as unique_together. While this may not be ideally for a few queries. It's good enough for most.

                If you update your question with the current table structure (as shown in your sql console) I will update my answer to show what the model will look like.

                Update There are lots of different ways in which you can drop the old composite primary key and replace it with a new auto increment primary key. Here is the easiest, it involves just SQL

                CREATE TABLE newtable LIKE mytable;
                ALTER TABLE newtable DROP PRIMARY KEY;
                ALTER TABLE newtable ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
                RENAME TABLE mytable to mytable_old;
                RENAME TABLE newtable to mytable;
                INSERT INTO mytable(userid,field1id, rest of the fields) 
                    SELECT * FROM mytable_old;
                

                Then edit your model and remove the primary_key=True flag from those fields.

                Footnote:
                Some databases like sqlite for example does not support the LIKE clause in a CREATE TABLE. In these cases, you will have to look up the create table statement for the original table, and copy paste after editing the table name. Judging by your table structure you seem to be using mysql and it supports the LIKE clause.

                这篇关于使用旧数据库在 django 项目中使用复合主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                相关文档推荐

                How to update a record using sequelize for node?(如何使用节点的 sequelize 更新记录?)
                How to provide a mysql database connection in single file in nodejs(如何在 nodejs 中的单个文件中提供 mysql 数据库连接)
                Looping Over Result Sets in MySQL(在 MySQL 中循环结果集)
                What is an efficient way of inserting thousands of records into an SQLite table using Django?(使用 Django 将数千条记录插入到 SQLite 表中的有效方法是什么?)
                Prevent Django SQLite db from being overwritten while pushing to Heroku(防止 Django SQLite 数据库在推送到 Heroku 时被覆盖)
                Writing an SQL query to SELECT item from the following table(编写 SQL 查询以从下表中选择项目)

                1. <legend id='QdPC3'><style id='QdPC3'><dir id='QdPC3'><q id='QdPC3'></q></dir></style></legend>

                2. <tfoot id='QdPC3'></tfoot>
                    <bdo id='QdPC3'></bdo><ul id='QdPC3'></ul>
                      <tbody id='QdPC3'></tbody>
                    <i id='QdPC3'><tr id='QdPC3'><dt id='QdPC3'><q id='QdPC3'><span id='QdPC3'><b id='QdPC3'><form id='QdPC3'><ins id='QdPC3'></ins><ul id='QdPC3'></ul><sub id='QdPC3'></sub></form><legend id='QdPC3'></legend><bdo id='QdPC3'><pre id='QdPC3'><center id='QdPC3'></center></pre></bdo></b><th id='QdPC3'></th></span></q></dt></tr></i><div id='QdPC3'><tfoot id='QdPC3'></tfoot><dl id='QdPC3'><fieldset id='QdPC3'></fieldset></dl></div>

                      <small id='QdPC3'></small><noframes id='QdPC3'>