Wednesday, September 15, 2010

Re: Initialize model's fields

On 15 sep, 18:35, marcovic <hicsuntmarco...@gmail.com> wrote:
> Hi all,
> i'm trying to do a simple task with Django but evidently it is not so
> simple...

It is - when you understand how things work.

> I have my model:
>
> class Mymodel(models.Model):
>     random_string = models.CharField(max_length=200)
>
>     def produce_string(self):
>          a = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "L", "M",
>             "N", "O", "P", "Q", "R", "S", "T", "U", "V", "Z", "0",
> "1", "2", "3", "4", "5", "6", "7", "8", "9"]
>         num = ""
>         random.shuffle(a)
>         for x in a[:8]:
>             num = num + x
>         self.random_string= num
>

import string

def random_string():
a = list(string.uppercase + string.digits)
random.shuffle(a)
return "".join(a[:8])

> What i'd like to do is having a random string stored into my new
> object as soon as i'll create my object. To do that i've inserted this
> method into previous code:
>
>  def __init__(self,*args, **kwargs):
>         super(Mymodel, self).__init__(*args, **kwargs)
>         self.produce_string()

__init__ is called on the class instanciation. Your model class is
instanciated each time you load a record from the db.

You could just use a pre_save signal and set the random_string field
if the "created" flag is True.

def mymodel_pre_save(sender, instance, created, **kw):
if created:
instance.random_string = random_string()

pre_save.connect(my_model_pre_save, sender=MyModel)


If you need to have this value set on new instances even before the
instance is saved, you can still set it in the initializer, but then
you need to test on self.pk before (assuming your using an auto_id)

def __init__(self, *args, **kw):
super(MyModel, self).__init__(*args, **kw):
if not self.pk:
self.random_string = random_string()

HTH

--
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 django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment