django - __init__ called when calling filter on foreign key concatenation -


i'm baffled one:

i have 3 models, chained foreign keys:

from django.db import models  class a(models.model):   name = models.charfield(max_length=100, unique=true)  class b(models.model):   = models.foreignkey(a)   name = models.charfield(max_length=100, unique=true)  class c(models.model):   b = models.foreignkey(b)   name = models.charfield(max_length=100, unique=true)          def __init__(self, *args, **kwargs):     import pdb; pdb.set_trace()     super(c, self).__init__(*args, **kwargs)     self.name = 'inited' 

when try list of instances of c point instance of a, c's __init__ gets called:

class simpletest(testcase):   def test_goes_to_init(self):     = a(name = 'a')     a.save()     b = b(name = 'b', = a)     b.save()     c = c(name = 'c', b = b)     c.save()     cs = c.objects.all().filter(b__a=a)     arr = [i in cs] # here c's __init__ gets called     self.assertequal(arr.__len__(), 1) 

why should be? there way generating array w/o calling __init__? in real application __init__ function slow, , should called rarely.

here's trace debugging session:

  /home/ranmoshe/sites/django/testttt/testing123/tests.py(13)test_goes_to_init() -> arr = [i in cs]   /usr/local/lib/python2.6/dist-packages/django/db/models/query.py(106)_result_iter() -> self._fill_cache()   /usr/local/lib/python2.6/dist-packages/django/db/models/query.py(760)_fill_cache() -> self._result_cache.append(self._iter.next())   /usr/local/lib/python2.6/dist-packages/django/db/models/query.py(282)iterator() -> obj = self.model(*row[index_start:aggregate_start]) > /home/ranmoshe/sites/django/testttt/testing123/models.py(16)__init__() -> super(c, self).__init__(*args, **kwargs) 

__init__ called each time python instance created. trying execute code when database record saved. this, should override model's save() method:

class c(models.model):     ...      def save(self, *args, **kwargs):         do_something()         super(c, self).save(*args, **kwargs) # call "real" save() method.         do_something_else() 

Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -