Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django random value for Model field

So I am able to generate a random id using uuid So far so good But when I try to database i get same value

 def f():
    d = uuid4()
    str = d.hex
    return str[0:16]

class Q(models.Model):
  a = models.CharField(max_length=150)
  b = models.IntegerField(max_length=25)
  c = models.IntegerField(max_length=32 , default=0)
  d = models.ManyToManyField(Ans , related_name='aa')
  e = models.CharField(max_length=18 , default = f() ,unique=True )


class Ans(models.Model):
  sub = models.CharField(max_length=150) 


-----------------------------------------------------------------

And I'm inserting like this

def ins(request):
     t =random.randint(0, 1000)
     p = Q(a = t , b=0 , c=0)
     p.save()
     return HttpResponse('Saved')

Just curious what the hell is happening here

Side note: If I set e.unique = False I get 2-3 with the same e values before I get a new UUID values

like image 244
Xtal Avatar asked Dec 11 '22 13:12

Xtal


1 Answers

You should not call the function that you are passing to default:

e = models.CharField(max_length=18, default=f, unique=True)

FYI, according to docs, you should pass a value or a callable:

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

like image 117
alecxe Avatar answered Dec 22 '22 16:12

alecxe