I am creating an where in my model Profile i am getting the default id with the name id, but the issue it is generating ids from 0 to onwards like 1,2,. What I want is a random id which should also be longer length like 343347 etc.
CodePudding user response:
Use a UUIDField
. Copied from the doc:
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
Note that a callable (with the parentheses omitted) is passed to default, not an instance of UUID.
CodePudding user response:
You can use the following code. But it is possible to have a duplicate number and make an error.
import random
def big_random():
return random.randint(1000000, 9999999)
class Foo(models.Model):
id = models.IntegerField(default=big_random, primary_key=True)
bar = models.CharField(max_length=30)
I suggest use uuid as pk:
import uuid
class Foo(models.Model):
id = models.IntegerField(default=uuid.uuid4, primary_key=True)
bar = models.CharField(max_length=30)
CodePudding user response:
If the requirement is for a unique 32-bit bit integer entity that can be used in place of a pk in URLs, you could use a reversible 1 to 1 mapping function within that domain. This would not be secure but would prevent people who do not have access to your source code from "fishing" for the next or previous pk.
Using CBVs, you would at one end decode the "pk" that isn't a pk, for example in a subclassed get_object
method, and at the other end generate URLs using for example
reverse( 'app:name', kwargs={ 'pk': my_mapping_function( object.pk) } )
I won't volunteer such a mapping function because by publishing it, I instantly render it far less useful! (A trivial one would be to permute the bits of the integer pk into a new order. Consult a mathematician for less trivial ones).
I still stand by my comment that this is an example of a wrong thing. If guessing pk values compromises application security, then "security by obscurity" is no better, and this answer is an example of such.
This said, Hashids might be useful.