简体   繁体   English

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

[英]Django raises MySQL error 1452 on object.save() but INSERT works

I am struggling with Django and MySQL on a 1452 error. 我在Django和MySQL上遇到1452错误。

I am trying to create a GoogleAnalyticsUserWebproperty object which has a foreign key pointing to GoogleAnalyticsUserAccount. 我正在尝试创建一个具有指向GoogleAnalyticsUserAccount的外键的GoogleAnalyticsUserWebproperty对象。 It fails, but when I try to INSERT directly in MySQL then it works fine. 它失败了,但是当我尝试直接在MySQL中插入时,它可以正常工作。

Here are my models: 这是我的模型:

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')

The related GoogleAnalyticsUserWebproperty model's MySQL table: 相关的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    |                |
[...]
+--------------------------+--------------+------+-----+---------+----------------+

The tables description given by SHOW TABLE STATUS: SHOW TABLE STATUS给出的表描述:

| | Name | 姓名| Engine | 引擎| Version | 版本| Row_format | 行格式| Rows | 行| Avg_row_length | Avg_row_length | Data_length | 数据长度| Max_data_length | Max_data_length | Index_length | 索引长度| Data_free | 无数据| Auto_increment | 自动递增| Create_time | 创建时间| Update_time | 更新时间| Check_time | 检查时间| Collation | 整理| Checksum | 校验和 Create_options | Create_options | Comment | 评论|

digger_googleanalyticsuseraccount | digger_googleanalytics用户帐户| InnoDB | InnoDB | 10 | 10 | Compact 紧凑
| | 1 | 1 | 16384 | 16384 | 16384 | 16384 | 0 | 0 | 32768 | 32768 | 4194304 | 4194304 | 2 | 2 | 2014-04-07 16:40:36 | 2014-04-07 16:40:36 | NULL | NULL | NULL | NULL | latin1_swedish_ci | latin1_swedish_ci | NULL | NULL | | | | |

digger_googleanalyticsuserwebproperty | digger_googleanalyticsuserwebproperty | InnoDB | InnoDB | 10 | 10 | Compact 紧凑
| | 1 | 1 | 16384 | 16384 | 16384 | 16384 | 0 | 0 | 49152 | 49152 | 4194304 | 4194304 | 4 | 4 | 2014-04-07 16:40:36 | 2014-04-07 16:40:36 | NULL | NULL | NULL | NULL | latin1_swedish_ci | latin1_swedish_ci | NULL | NULL | | | | | | |

Django's code failing (a GoogleAnalyticsUserAccount is found so there should not be any problem here): 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's related error message: Django的相关错误消息:

(1452, 'Cannot add or update a child row: a foreign key constraint fails ( cpu . digger_googleanalyticsuserwebproperty , CONSTRAINT related_account_id_refs_id_e855a0a4 FOREIGN KEY ( related_account_id ) REFERENCES digger_googleanalyticsuseraccount ( id ))') (1452,“不能添加或更新子行,外键约束失败( cpudigger_googleanalyticsuserwebproperty ,约束related_account_id_refs_id_e855a0a4外键( related_account_id )参考digger_googleanalyticsuseraccountid ))”)

And finally the INSERT which works just fine: 最后是可以正常工作的INSERT:

insert into digger_googleanalyticsuserwebproperty values(1, 1, 1, 1, [...]);

So I made sure that the tables are INNODB and that a GoogleAnalyticsUserAccount object exists with the pk=1. 因此,我确保表是INNODB,并且存在一个pk = 1的GoogleAnalyticsUserAccount对象。

What could I be missing here? 我在这里可能想念什么?

Edit: 编辑:

The account object in Python code gives me: Python代码中的account对象为我提供了:

print(a) # "boom-bike.info 48361394 (admin)" (from custom __unicode__)
print(a.pk) # 1

An interesting part of the stack trace: 堆栈跟踪中一个有趣的部分:

/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)'

So it seems that digger_googleanalyticsuseraccount.account_id is used ('48361394' in Django's generated sql, the second parameter) instead of digger_googleanalyticsuseraccount.id as the foreign key value. 因此,似乎使用了digger_googleanalyticsuseraccount.account_id(在Django生成的sql中为“ 48361394”,第二个参数)代替了digger_googleanalyticsuseraccount.id作为外键值。 How may I make Django use 'id' (the digger_googleanalyticsuseraccount primary key) instead of account_id?? 如何使Django使用“ id”(digger_googleanalyticsuseraccount主键)代替account_id?

You can explicitly set the related_account_id to a.id as follows: 您可以按如下所示将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'],
                                   [...])

Well I somehow figured out what was wrong: GoogleAnalyticsUserWebproperty contained the following fields: "account" (foreign key) and "account_id" (a string). 好吧,我以某种方式找出了问题所在:GoogleAnalyticsUserWebproperty包含以下字段:“ account”(外键)和“ account_id”(字符串)。 I changed "account_id" to "webproperty_account_id" and it fixed the unexpected Django behavior. 我将“ account_id”更改为“ webproperty_account_id”,并修复了意外的Django行为。 FYI, I'm using Django 1.6.2. 仅供参考,我正在使用Django 1.6.2。

Thanks for your help! 谢谢你的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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