简体   繁体   中英

Generate Django “unique_together” key with “id” field

Here is the model

class MyModel(models.Model):
    id = models.CharField(max_length=10, primary_key=True)
    password = models.CharField(max_length=25)
    area = models.CharField(max_length=100, primary_key=True)

    def __unicode__(self):
        return "%s from %s" % (self.id, self.area)

    class Meta:
        unique_together = (("id", "area"),)

I am trying to generate a unique key using Django's built-in Id functionality without making Id as a primary key.

Possible?

I do not think you can have a primary key based on multiple column (cf. django doc : https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys ).

Only unique_together will still work.

In case what you want is an auto incremented field which is not a primary key :

AutoField¶

class AutoField(**options)¶ An IntegerField that automatically increments according to available IDs. You usually won't need to use this directly; a primary key field will automatically be added to your model if you don't specify otherwise. See Automatic primary key fields.

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