简体   繁体   中英

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

I am struggling with Django and MySQL on a 1452 error.

I am trying to create a GoogleAnalyticsUserWebproperty object which has a foreign key pointing to GoogleAnalyticsUserAccount. It fails, but when I try to INSERT directly in MySQL then it works fine.

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:

+--------------------------+--------------+------+-----+---------+----------------+
| 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:

| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |

digger_googleanalyticsuseraccount | InnoDB | 10 | Compact
| 1 | 16384 | 16384 | 0 | 32768 | 4194304 | 2 | 2014-04-07 16:40:36 | NULL | NULL | latin1_swedish_ci | NULL | | |

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

Django's code failing (a GoogleAnalyticsUserAccount is found so there should not be any problem here):

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:

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

And finally the INSERT which works just fine:

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.

What could I be missing here?

Edit:

The account object in Python code gives me:

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. How may I make Django use 'id' (the digger_googleanalyticsuseraccount primary key) instead of account_id??

You can explicitly set the related_account_id to a.id as follows:

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). I changed "account_id" to "webproperty_account_id" and it fixed the unexpected Django behavior. FYI, I'm using Django 1.6.2.

Thanks for your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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