Wednesday, September 15, 2010

Re: Initialize model's fields

Your produce_string method is being run not just every time you create
a new Mymodel, but every time you load an existing one from the
database -- so it's overwriting your random strings on load. You'd
probably do better producing the random strings in the save() method.

On Sep 15, 12:35 pm, marcovic <hicsuntmarco...@gmail.com> wrote:
> Hi all,
> i'm trying to do a simple task with Django but evidently it is not so
> simple...
>
> 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
>
> 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()
>
> So running django's shell, everything seems to work fine...
>
> from test.testing.modules import Mymodel
> m = Mymodel()
> m.random_string
>
> > "23467.."
> m.save()
> >OK
>
> But if i try to get all objects saved into my db (so using
> Mymodel.objects.all()) what i get is a different result every time i
> run this command.
> What i've noticed is that Mymodel.objects.all() run "__init__" method
> inside my class, so what i got as results is everytime a different
> results set (random_string is not the one stored into db but a random
> one produced by produce_string method).
>
> What's wrong with this code? Am i missing something?
>
> Many thanks in advance

--
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