简体   繁体   中英

Django custom primary key id null error

Consider this model:

class Organisation(models.Model):
    ref = models.CharField(max_length=50, primary_key=True)
    type = models.IntegerField(choices=ORGANISATION_TYPE_CHOICES, blank=True, null=True)
    org_name = models.CharField(max_length=255)
    org_name_lang = models.CharField(max_length=255, blank=True, null=True)

    date_created = models.DateTimeField(auto_now_add=True, editable=False)
    date_updated = models.DateTimeField(auto_now=True, editable=False)

I get this error on creation, however the instance IS in fact saved:

django.db.utils.IntegrityError: (1048, "Column 'organistion_id' cannot be null")

Running the create again:

django.db.utils.IntegrityError: (1062, "Duplicate entry 'GB-CHC-202918' for key 'PRIMARY'")

I'm using mysql, and haven't worked with character primary keys, am I missing out on something?

update: SOLVED (there was a related model with a custom save method)

Each model in Django also has a field id which is automatically added and which is used as primary key (see Automatic primary key fields ). Django won't add the id field when you specify a primary key but since you're getting this error, I'm thinking that you've added your own primary key after creating the table?

If so, you could drop the table and recreate it ( syncdb ) or add a database migration to modify the table structure (eg, using south ).

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