[英]Django raises MySQL error 1452 on object.save() but INSERT works
我在Django和MySQL上遇到1452錯誤。
我正在嘗試創建一個具有指向GoogleAnalyticsUserAccount的外鍵的GoogleAnalyticsUserWebproperty對象。 它失敗了,但是當我嘗試直接在MySQL中插入時,它可以正常工作。
這是我的模型:
class GoogleAnalyticsUserAccount(models.Model):
user = models.ForeignKey(User)
account_id = models.CharField(max_length=64)
[...]
class Meta:
unique_together = ('user', 'account_id')
class GoogleAnalyticsUserWebproperty(models.Model):
user = models.ForeignKey(User)
account = models.ForeignKey(GoogleAnalyticsUserAccount,
db_column='related_account_id',
on_delete=models.CASCADE)
webproperty_id = models.CharField(max_length=64)
class Meta:
unique_together = ('user', 'account', 'webproperty_id')
相關的GoogleAnalyticsUserWebproperty模型的MySQL表:
+--------------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | MUL | NULL | |
| related_account_id | int(11) | NO | MUL | NULL | |
| webproperty_id | varchar(64) | NO | | NULL | |
[...]
+--------------------------+--------------+------+-----+---------+----------------+
SHOW TABLE STATUS給出的表描述:
| 姓名| 引擎| 版本| 行格式| 行| Avg_row_length | 數據長度| Max_data_length | 索引長度| 無數據| 自動遞增| 創建時間| 更新時間| 檢查時間| 整理| 校驗和 Create_options | 評論|
digger_googleanalytics用戶帳戶| InnoDB | 10 | 緊湊
| 1 | 16384 | 16384 | 0 | 32768 | 4194304 | 2 | 2014-04-07 16:40:36 | NULL | NULL | latin1_swedish_ci | NULL | | |digger_googleanalyticsuserwebproperty | InnoDB | 10 | 緊湊
| 1 | 16384 | 16384 | 0 | 49152 | 4194304 | 4 | 2014-04-07 16:40:36 | NULL | NULL | latin1_swedish_ci | NULL | | | |
Django的代碼失敗(找到了GoogleAnalyticsUserAccount,因此這里應該沒有任何問題):
for webproperty in webproperties:
try:
GoogleAnalyticsUserWebproperty.objects.get(user=user,
webproperty_id=webproperty['id'])
except GoogleAnalyticsUserWebproperty.DoesNotExist:
a = GoogleAnalyticsUserAccount.objects.get(user=user,
account_id=webproperty['accountId'])
w = GoogleAnalyticsUserWebproperty(user=user,
account=a,
webproperty_id=webproperty['id'],
[...])
w.save()
Django的相關錯誤消息:
(1452,“不能添加或更新子行,外鍵約束失敗(
cpu
。digger_googleanalyticsuserwebproperty
,約束related_account_id_refs_id_e855a0a4
外鍵(related_account_id
)參考digger_googleanalyticsuseraccount
(id
))”)
最后是可以正常工作的INSERT:
insert into digger_googleanalyticsuserwebproperty values(1, 1, 1, 1, [...]);
因此,我確保表是INNODB,並且存在一個pk = 1的GoogleAnalyticsUserAccount對象。
我在這里可能想念什么?
編輯:
Python代碼中的account對象為我提供了:
print(a) # "boom-bike.info 48361394 (admin)" (from custom __unicode__)
print(a.pk) # 1
堆棧跟蹤中一個有趣的部分:
/var/local/virtualenvs/cpu-dev/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py in execute_sql
cursor.execute(sql, params) ...
▼ Local vars Variable
Value cursor
<django.db.backends.util.CursorDebugWrapper object at 0xa65b0ec> self
<django.db.backends.mysql.compiler.SQLInsertCompiler object at 0xa65b94c>
return_id True
params [1, 48361394, 1, u'XXX', u'STANDARD', u'79873902', u'ONLINE_COMMUNITIES', u'effective', u'UA-XXX', u'analytics#webproperty', u'48361394', u'http://boom-bike.info', u'https://www.googleapis.com/analytics/v3/management/accounts/XXX/webproperties/UA-48361394-1', u'2014-02-24 12:16:30', u'2014-02-24 12:16:36', u'https://www.googleapis.com/analytics/v3/management/accounts/XXX', u'analytics#account', u'https://www.googleapis.com/analytics/v3/management/accounts/XXX/webproperties/UA-48361394-1/profiles', u'analytics#profiles']
sql u'INSERT INTO `digger_googleanalyticsuserwebproperty` (`user_id`, `related_account_id`, `profile_count`, `name`, `level`, `internal_web_property_id`, `industry_vertical`, `permissions`, `webproperty_id`, `kind`, `account_id`, `website_url`, `self_link`, `created`, `updated`, `parent_link_href`, `parent_link_type`, `child_link_href`, `child_link_type`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
因此,似乎使用了digger_googleanalyticsuseraccount.account_id(在Django生成的sql中為“ 48361394”,第二個參數)代替了digger_googleanalyticsuseraccount.id作為外鍵值。 如何使Django使用“ id”(digger_googleanalyticsuseraccount主鍵)代替account_id?
您可以按如下所示將a.id
顯式設置為a.id
:
w = GoogleAnalyticsUserWebproperty(user=user,
related_account_id=a.id, #might be account_id instead of related_account_id
webproperty_id=webproperty['id'],
[...])
好吧,我以某種方式找出了問題所在:GoogleAnalyticsUserWebproperty包含以下字段:“ account”(外鍵)和“ account_id”(字符串)。 我將“ account_id”更改為“ webproperty_account_id”,並修復了意外的Django行為。 僅供參考,我正在使用Django 1.6.2。
謝謝你的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.