0

How can I set something like id which would be unique and generated after creating an object?

I would like to assign identifier for each object so user can indentify product by this id but I don't want it to be regular autoincrement id because I want it let's say consists of 10 digit. (my pk's are 1,2...inf).

What I've done so far is that I've tried to create a hash of the name but it's not a good way to do that.

class Job(models.Model):
    job_id = models.BigIntegerField() # or hash(something)
    customer = models.ForeignKey(User, related_name='orders', help_text=_("Customer"), on_delete=models.CASCADE)
    translator = models.ForeignKey(User, related_name='jobs', null=True, blank=True, help_text=_(u"Translator"))
    price = models.FloatField(null=True, blank=True, help_text=_(u"Price"))

One possible way would be to create a post_save signal which would generate random 10 digit number and then check for uniqueness but it's probably very consuming solution.

Milano
  • 18,048
  • 37
  • 153
  • 353

1 Answers1

0

You can use UUIDField instead:

A field for storing universally unique identifiers. Uses Python’s UUID class. When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32).

Universally unique identifiers are a good alternative to AutoField for primary_key. The database will not generate the UUID for you, so it is recommended to use default:

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 didn't mentioned used RDMBS, but PostgreSQL has better support for UUID, you can read more here.

arogachev
  • 33,150
  • 7
  • 114
  • 117
  • Thanks, since project is in progress, I don't want to mess id's and uuid. I want just not PK, unique, identifier for users. So do I have to change primary_key to unique? – Milano May 20 '16 at 09:06
  • I don't get it. You asked about alternative, here it is. Primary key is always unique, see [here](http://stackoverflow.com/questions/30911898/mysql-is-primary-key-unique-by-default). – arogachev May 20 '16 at 09:08
  • Mixing both is not recommended. It's better to use either id or uuid. – arogachev May 20 '16 at 09:16