我有一个旧数据库,其中一些表包含复合主键。我通过运行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(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'),)
我可以正常获取数据。但是,当我想save()
在某个模型实例上运行命令时,就会出现问题。django 执行的查询不正确。例如:
>>> 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'}
但是我需要:
{'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
.
编辑:添加旧表结构
+------------+------------+------+-----+---------+-------+
| 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 | |
+------------+------------+------+-----+---------+-------+