Malcolm Tredinnick wrote:
> The reason you are getting the same values all the time is because the
> random.randint(1,1000) and time.time() calls are being evaluated when
> the CharFiueld instance is created, which is at your model *class*
> creation time (i.e. import time, essentially). Not when you create a
> model instance.
>
> What you want is to pass in a callable for the default value (not the
> result of calling the callable, which is what you are doing now). See
> http://www.djangoproject.com/documentation/models/field_defaults/ for an
> example.
>
> Another way to do this would be to create the value as part of your
> save() method, if it was dependent on other things. But for a simple
> thing like time.time, just using a callable default will do.
>
> Realise that for your random.randint case, you will need to create a
> function that returns a new value in the range when it is called. You
> could use
>
>         lambda: random.randint(1, 1000)
>
> and it should work.
>
> Regards,
> Malcolm


Thanks for the clue, it's quite obvious to me now but this morning 5am
it wasn't, especially because the admin interface didn't give me always
the same random/unique values. I think that might have been caused by
the different python processes - I was running django behind
apache/fcgi. But now everything is clear:


from time import time
from random import WichmannHill
class Tester(models.Model):
    timetest1 = models.CharField( maxlength=20, default=time )
    timetest2 = models.CharField( maxlength=20, default=time() )
    rangetest1 = models.CharField( maxlength=5,
default=lambda:WichmannHill().randint(0,10000) )
    rangetest2 = models.CharField( maxlength=5,
default=WichmannHill().randint(0,10000) )
    class Meta:
        db_table = 'test'
    class Admin:
        pass
    def __str__(self):
        return self.timetest1


# python manage.py syncdb
Creating table test
#python manage.py shell
>>> from myproject.myapp.models import Tester
>>> for i in range(0,50):
...     e = Tester()
...     e.save()

produces unique values for timetest1 and rangetest1 but same values for
timetest2 and rangetest2. obviously.
not so if creating records through the admin (apache/fcgi and must be 5
processes):

timetest2, rangetest2
1154602130.49, 44216
1154602118.07, 70639
1154602122.32, 70880
1154602125.78, 57792
1154602133.45, 59665
1154602130.49, 44216
1154602118.07, 70639
1154602122.32, 70880
1154602125.78, 57792
1154602133.45, 59665
1154602125.78, 57792
...

thanks again,
bernie


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to