繁体   English   中英

Django在object.save()上引发MySQL错误1452,但是INSERT可以工作

[英]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,“不能添加或更新子行,外键约束失败( cpudigger_googleanalyticsuserwebproperty ,约束related_account_id_refs_id_e855a0a4外键( related_account_id )参考digger_googleanalyticsuseraccountid ))”)

最后是可以正常工作的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM