在Django中更新一对多引用字段也会更新其他对象



我有一个现有的DB,它有两个表,名为Identities和Accounts,我正试图使用Django ORM来管理它们。

Identities与Accounts有一对多的关系,我对这两个表进行了如下建模:

class Identity(models.Model):
    class Meta:
        managed = False
        db_table = "Identities"
    i_id = models.AutoField(db_column = "I_ID", primary_key = True) 
    name = models.CharField(db_column = "DisplayName", max_length = 200)
class Account(models.Model):
    class Meta:
        managed = False
        db_table = "Accounts"
    name = models.CharField(db_column = "Name", max_length = 200, primary_key = True)
    identity = models.ForeignKey("Identity", db_column = "I_ID", blank = True, null = True, related_name = "accounts")

我的问题是,当我更新与帐户关联的身份时,所有与新身份关联的帐户都将切换到新身份:

old_identity = Identity.objects.create(name = "Old")
new_identity = Identity.objects.create(name = "New")
account_1 = Account.objects.create(name = "account_1", identity = old_identity)
account_2 = Account.objects.create(name = "account_2", identity = old_identity)
# change the identity for account_1:
account_1.identity = new_identity
account_1.save()
# read account_2 from DB and check identity
account_2 = Account.objects.get(name = "account_2")
# identity is now "New" also for account_2!
print account_2.identity.name 

如果我直接在DB中进行相同的更新,那么只有我更改的帐户的身份发生了更改,而不是所有与该身份相关的帐户,所以这是Django引入的。

更改identity字段时,如果只更新一个帐户,该怎么办?

注意:需要明确的是,数据库中的两个引用也都发生了更改,这不是数据未刷新之类的问题。

从已发布的相关代码中检查问题。发布的代码按预期运行:

创建表格:

(venv)dani@egg-v3:~/tmp/lldldl/paolo$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: mytest
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Creating table mytest_identity
    Creating table mytest_account
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying sessions.0001_initial... OK

运行:

(venv)dani@egg-v3:~/tmp/lldldl/paolo$ python manage.py shell
Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from mytest.models import Account,Identity
>>> old_identity = Identity.objects.create(name = "Old")
>>> new_identity = Identity.objects.create(name = "New")
>>> account_1 = Account.objects.create(name = "account_1", 
                                       identity = old_identity)
>>> account_2 = Account.objects.create(name = "account_2", 
                                       identity = old_identity)
>>> 
>>> # change the identity for account_1:
>>> account_1.identity = new_identity
>>> account_1.save()
>>> 
>>> # read account_2 from DB and check identity
>>> account_2 = Account.objects.get(name = "account_2")
>>> 
>>> # identity is now "New" also for account_2!
>>> print account_2.identity.name 
Old
>>> 

使用django 1.7和sqlite3进行了测试。也许是一些数据库触发器?后置/预存信号?

最新更新