views:

403

answers:

2

Below I call the same methods in author and w5 model objects. But one of them raises an error:

>>> author = models.Author('ali')
>>> author.article_set.count()
---------------------------------------------
ValueError: invalid literal for int() with base 10: 'ali'

>>> w5 = models.Author(name='w5')
>>> w5.article_set.count()
0

Actually, before these lines I had previously a wrong Author class definition. I obtained the ValueError from author object first with that former definition of Author. Then I changed Author class and reloaded the modules.

After reloading the models with the reloadmodels.py written by Chad Braun-Duin, newly instantiated objects like w5 work properly. But reinstantiated objects like author raise errors.

Is this contradictory behavior due to django's query caching logic or reloadmodels.py? Have any idea?

Thanks...

A: 

If you change the model definitions in django, you need to re-apply your changes to the database. If you can manually drop the tables, you can restore the structure with manage.py syncdb

You can use the manage.py sql command to examine the SQL definitions that django would use to match your new model class, and manually edit the tables to fit, if you'd rather not lose the table.

cms
I didn't change model definitions. I had only changed business logic.
Mert Nuhoglu
I misunderstood, from where you said you changed the Author class definition, I thought that referred to a model change.
cms
+1  A: 

This isn't anything to do with Django, it's a Python thing. In the linked question, Chad was importing models like this:

import myapp.models as mymodels

Using this syntax, you can use reload() to refresh class definitions when you change them on disk. However, it's far more standard to import your models like this:

from myapp.models import MyModel

If you do this - and most people do - reload() has no effect, even with Chad's hack.

Really, it's more simple to just quit the Python shell and restart it - especially if you use shell_plus from django-extensions which automatically loads your models into the shell on startup.

Daniel Roseman
Thanks for the info. You are right, my code imports the models with "from ... import ..." command.I will check shell_plus. But the problem with restart is that it takes a little time to start ipython shell. But anyway reloading statements take time too.
Mert Nuhoglu