[Fixed]-Custom id field in Django model

27👍

https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields

If you’d like to specify a custom primary key, just specify
primary_key=True on one of your fields. If Django sees you’ve
explicitly set Field.primary_key, it won’t add the automatic id
column.

So you want (from https://docs.djangoproject.com/en/dev/ref/models/fields/#uuidfield)

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # other fields

you don’t have to name the field id I think.

👤eugene

0👍

On my project, this is what I did. Supposed that you have a sample model with a custom id and the autofield ID:

class Product(models.Model)
      product_tag_number = models.CharField(max_length=50, editable=False, unique=True) # this is my custom ID
      
      def save(self, *args, **kwargs): # I override my save function in here. 
            super().save(*args, **kwargs)
            self.set_ptn() # And then call my own function in here to generate such custom ID combining the autoField ID and the UUID.

      def set_ptn(self): # And this is the function for generating the custom ID for the item
            ......
            And then your function goes here for combining them
            ......

Note: Doing this method will not affect and will not use the AutoField generated by Django for you. But it’s your call if you will use this as your primary key.

Leave a comment