简体   繁体   中英

Populate unique ID in Django Rest Framework

I am trying to make my ID in class Animal unique, so that it automatically increments without a user having to add data into the filed (so the filed is hidden), but I can't figure out how to do it.

Right now I have this in my models.py :

 class Animal(models.Model):
    id = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4, primary_key=True)
    name = models.CharField(max_length=200)

Which in my mind will have to make id unique, but currently it doesn't do anything.

Here is my serialisers.py for reference:

class AnimalSerialiser(serializers.HyperlinkedModelSerializer):

    doctor = DoctorSerealiser(read_only=True)


    class Meta:
        model = Animal
        fields = ('id' , 'name' , 'gender' , 'breed' , 'adoption' , 'vaccines', 'doctor')

As other people have mentioned in the comments, you're defining your model wrong. Django adds an auto-incrementing field by default. Take a look at the docs for more information - https://docs.djangoproject.com/en/1.9/topics/db/models/#automatic-primary-key-fields .

You really just need:

class Animal(models.Model):
    name = models.CharField(max_length=200)

and then you can still access that field like animal.id .

And UUID's are totally different than an auto-incrementing ID. See the wiki - they're basically just strings that are nearly impossible to generate duplicates of.

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