Django 1.7 makemigrations - ValueError: Cannot serialize class - python

I'm running into an interesting issue with an upgrade from Django 1.6.11 to 1.7. It seems to be based on how I am currently splitting up files. Currently, model methods are stored in separate files from the models, due to the massive amount of methods.
For example it is split up as follows:
help
|_ modelmethods
| |_ __init__.py
| |_ thread_methods.py
|_ __init__.py
|_ models.py
The __init__.py in the help app folder looks like so:
""" __init__.py for help app."""
from help.modelmethods.thread_methods import *
And thread_methods.py looks like this:
"""Methods for the Thread model."""
from help.models import Thread
class ThreadMethods:
"""Adds methods on to the Thread model."""
def do_the_thing(self):
pass
Thread.__bases__ += (ThreadMethods,)
The error that I'm seeing from this is as follows:
Migrations for 'help':
0001_initial.py:
- Create model Thread
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 124, in handle
self.write_migration_files(changes)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files
migration_string = writer.as_string()
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 129, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 86, in serialize
arg_string, arg_imports = MigrationWriter.serialize(arg_value)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 245, in serialize
item_string, item_imports = cls.serialize(item)
File "/Users/user/.virtualenvs/stuff/lib/python2.7/site-packages/django/db/migrations/writer.py", line 380, in serialize
raise ValueError("Cannot serialize: %r\nThere are some values Django cannot serialize into migration files.\nFor more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing" % value)
ValueError: Cannot serialize: <class help.modelmethods.thread_methods.ThreadMethods at 0x1105c3870>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing
I realize that it is attempting to serialize the class and choking on it. Is there a good way to fix this and keep the separation? Or would the only comparable way be to break up the models.py file into a models folder with the proper __init__.py setup and each file be dedicated to one model that also contains all the relevant methods (as well as making sure no circular imports were introduced).

I was unable to migrate because of a custom validator. My problem was that I have not read the manual properly, where it says:
If a class-based validator is used in the validators model field
option, you should make sure it is serializable by the migration
framework by adding deconstruct() and __eq__() methods.
Which points to the migrations-docs which explain why you need the deconstruct() and __eq__() and how to write them.
Should also work for other classes and not just for validators.

This can happen due to many reasons, in my case it was I set default=User.pk for user Which was causing the issue. My django version is 1.9
class Blog(models.Model):
title = models.CharField(max_length=200)
content = HTMLField()
pub_date = models.DateTimeField('date published', auto_now_add=True)
last_updated = models.DateTimeField('date published',default=timezone.now)
user = models.ForeignKey(User, default=User.pk)#wrong
user = models.ForeignKey(User, default=1)#correct, use any default value
featured = models.ImageField(upload_to = 'featured', blank=True)

You need to derive your method-models from object class, also try deriving Thread from ThreadMethods instead of adding it to the __bases__.
class ThreadMethods(object):
# ....

Related

Why is Django unable to run properly?

I am recently working on Django following the description from the book Python Crash Course. I followed every step and tried to restart from the beginning a couple of times, still unable to solve the problem(Even reinstalled MacOS to get a cleaner desktop). Here is my code:
class Topic(models.Model):
'''A topic the user is learning about'''
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
'''Return a string represent model'''
return self.text
The tracebacks are below:
Traceback (most recent call last):
File "/Users/bryan/Desktop/python/learning_log/learning_logs/models.py", line 3, in <module>
class Topic(models.Model):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 108, in __new__
app_config = apps.get_containing_app_config(module)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
self.check_apps_ready()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 135, in check_apps_ready
settings.INSTALLED_APPS
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 63, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
[Finished in 304ms with exit code 1]
[cmd: ['python3', '-u', '/Users/bryan/Desktop/python/learning_log/learning_logs/models.py']]
[dir: /Users/bryan/Desktop/python/learning_log/learning_logs]
[path: /Library/Frameworks/Python.framework/Versions/3.10/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
Edit:
The code is in the file models.py
It seems like the error is happening because you're running the models.py file directly. In working with Django, you rarely run a .py file directly. Usually you run some commands in the terminal, and then you interact with your project in a browser.
Are you working in an active virtual environment?
Have you run the makemigrations command for your app?
Have you run python manage.py migrate?
What happens when you run python manage.py runserver?
There is small mistake you are trying to access the text in __str__ method and due to which it failed in order to access the text you need to change the code like self.text
def __str__(self):
'''Return a string represent model'''
return self.text

Django Migrations Circular Dependencies

so my django project was working completely fine and everything worked.
I wanted to rename an app something else so I did and updated all the associated files in including the app.py config file.
I also cleared the database and removed all migration files from each app.
Ever since then I have never been able to finish makemigrations onto my apps.
I even recreated the app I renamed, by doing django-admin startapp "appname" and then copied the contents of models.py admin.py, etc over to see if I somehow cause an internal issue but I just can't figure out what's going on?.
I did manage to get all the makemigrations to success for all apps including the one I remade when I removed this (below) from another apps admin.py file
# accounts/admin.py
class SigBotSettingsInLine(admin.StackedInline):
model = SigBotSettings
#admin.register(Bot)
class BotAdmin(admin.ModelAdmin,):
...
inlines = [SigBotSettingsInLine]
but in the end the python manage.py migrate, still Failed. If someone would help it would be highly appreciated.
Here is the error-code:
(dguacENV) PS C:\Users\Admin\Desktop\djangoProjects\dguac> python manage.py makemigrations accounts
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\commands\makemigrations.py", line 88, in handle
loader = MigrationLoader(None, ignore_no_migrations=True)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__
self.build_graph()
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\db\migrations\loader.py", line 286, in build_graph
self.graph.ensure_not_cyclic()
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\db\migrations\graph.py", line 274, in ensure_not_cyclic
raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle))
django.db.migrations.exceptions.CircularDependencyError: accounts.0001_initial, accounts.0002_auto_20210809_1814, signals.0001_initial
Dependencies in accounts/migrations/0001_initial.py
dependencies = [
('signals', '__first__'),
('auth', '0012_alter_user_first_name_max_length'),
]
Dependencies in accounts/migraitons/0002_auto_20210809_1910.py
dependencies = [
('accounts', '0001_initial'),
]
Dependencies in signals/migrations/0001_initial.py
dependencies = [
('accounts', '0002_auto_20210809_1910'),
]
Dependencies in accounts/migrations/0001_initial.py
dependencies = [
('signals', '__first__'),
('auth', '0012_alter_user_first_name_max_length'),
]
Dependencies in accounts/migraitons/0002_auto_20210809_1910.py
dependencies = [
('accounts', '0001_initial'),
]
Dependencies in signals/migrations/0001_initial.py
dependencies = [
('accounts', '0002_auto_20210809_1910'),
]
This tells us the following:
accounts.0001.initial depends on signals.0001_initial (specified by '__first__'.
accounts.0002_auto_20210809_1910 depends on accounts.0001.initial
signals.0001_initial.py depends on accounts.0002_auto_20210809_1910
The circularity should be clear.
You can either edit these dependencies manually or delete all migrations and generate them again with ./manage.py makemigrations This should solve the problem unless there are underlying issues with the model dependencies themselves.
WARNING
Be very careful when editing or deleting migrations. If your project is deployed to a live server, editing migrations that have already applied will at best do nothing and at worst completely wreck your production database. The proceeding suggestion should only be used if you are working on a project that has not yet been deployed.
SOLVED:
So yes thank you a lot for pointing out about the migration dependency issue, reading that link made me clearly understand how the makemigrations function works.
So after I looked through my dependencies, I found that in my Signals.models file there was a foriegnkey that linked to the Signals app before it was migrated.
I commented out this foreignkey line then migrated and everything worked perfectly.
I even added the foreignkey back afterwards and updated the migration which also worked because at this point the signal database had already been migrated.
I know this is bad practice though and will he changing the way that foreignkey is linked through another method.
Appreciate the help.

Using Django, how do I add a foreign key column that references the same table? [duplicate]

This question already has answers here:
Django self-referential foreign key
(4 answers)
Closed 6 years ago.
I want a table to include a foriegn key field to itself, and have tried the following code:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class CollectionModel(models.Model):
parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE)
This produces the following error:
$ ./manage.py makemigrations eav
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
django.setup()
File "/usr/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/username/Documents/devel/python/project/eav/models.py", line 7, in <module>
class CollectionModel(models.Model):
File "/home/username/Documents/devel/python/project/eav/models.py", line 8, in CollectionModel
parent = models.ForeignKey(CollectionModel, on_delete=models.CASCADE)
NameError: name 'CollectionModel' is not defined
How do I include a foriegn key to the same table as a field?
As per https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey:
To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).
The above code should be changed to:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class CollectionModel(models.Model):
parent = models.ForeignKey('self', on_delete=models.CASCADE)
You need to add the below line to your model's
parent = models.ForeignKey('self', blank=True, null=True)
So, your model looks like,
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class CollectionModel(models.Model):
parent = models.ForeignKey('self', blank=True, null=True)

Extending Zinnia Entry

i am currently working on a website where i want to use django-blog-zinnia with django-cms. I have to extend the entry by a foreign key to another so i followed the documentation on the zinnia website.
I wrote the zinnia_extra/models.py:
from django.db import models
from zinnia.models_bases.entry import AbstractEntry
class AssociationBlog(AbstractEntry):
association = models.ForeignKey("associations.Association",
blank=True,
default=None,
null=True,
related_name='news')
def __str__(self):
return 'AssociationBlog %s' % self.title
class Meta(AbstractEntry.Meta):
abstract = True
Now i came to the south part wich was a painful lesson of underdocumentation. After several hours of reading several answers here i found out that setting up the south migration modules mean something like this:
SOUTH_MIGRATION_MODULES = {
'zinnia': 'zinnia_extra.migrations.zinnia',
}
After that i added
ZINNIA_ENTRY_BASE_MODEL = 'zinnia_extra.models.AssociationBlog'
and also i built a zinnia_extra/admin.py:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from zinnia.models.entry import Entry
from zinnia.admin.entry import EntryAdmin
class AssociationBlogAdmin(EntryAdmin):
fieldsets = ((_('Content'), {'fields': (
('title', 'status'), 'content', 'image', 'association')}),) + \
EntryAdmin.fieldsets[1:]
admin.site.unregister(Entry)
admin.site.register(Entry, AssociationBlogAdmin)
(which is like in the documentation)
to the settings.py. South works as expected with an resolved migration error that is actually unresolved. But i managed to get that. But my extra field is not in the Admin area. I searched around and found out that i have to add the extra to the INSTALLED_APPS, so they now look like that:
INSTALLED_APPS = (
... ,
'zinnia',
'cmsplugin_zinnia',
'zinnia_ckeditor',
'zinnia_extra'
)
which is actually also found in the documentation (http://docs.django-blog-zinnia.com/en/latest/how-to/extending_entry_model.html).
But now i get an error like this:
Unhandled exception in thread started by <function wrapper at 0x1082ad9b0>
Traceback (most recent call last):
File "/myproject/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 101, in inner_run
self.validate(display_num_errors=True)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name, True)
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('%s.models' % app_name)
File "/myproject/venv/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/myproject/venv/lib/python2.7/site-packages/zinnia/models/__init__.py", line 4, in <module>
from zinnia.models.entry import Entry
File "/myproject/venv/lib/python2.7/site-packages/zinnia/models/entry.py", line 6, in <module>
class Entry(load_model_class(ENTRY_BASE_MODEL)):
File: "/myproject/venv/lib/python2.7/site-packages/zinnia/models_bases/__init__.py", line 20, in load_model_class
raise ImproperlyConfigured('%s cannot be imported' % model_path)
django.core.exceptions.ImproperlyConfigured: zinnia_extra.models.AssociationBlog cannot be imported
I've searched for several hours now, but i am at the end and don't know how to search for this error type. Can someone provide an tutorial on the current extension workflow or help me with this error?
It seems the problem is the importation of zinnia_extra model.
Could be possible you need to add this line:
from zinnia_extra.models import AssociationBlog
in some file ?
I'm not sure in wich file, but it seems Django can't import your created class.
Maybe you need to add this import to your admin.py or other file where Django uses AssociationBlog
Other idea that comes to my mind is:
Could be that you need to add the zinnia_extra path to Python Path ? Is it in the same path as your project or same path as zinnia app?

'RelationshipProperty' object has no attribute 'c' error in sqlalchemy

I'm having a lot of trouble implementing SQLalchemy for a legacy MSSQL database. It is a big existing database, so I wanted to use sqlautocode to generate the files for me, because using autoload to reflect the database takes too long.
The first problem was that sqlautocode no longer seems to work on SQLalchemy 0.8. I did still have existing output from an earlier version, so I thought I'd use that, just to test with.
Now sqlautocode outputs the 'classical mapping', which is not really a problem, but whenever I tried to use a foreign key, 'RelationshipProperty' object has no attribute 'c' would show up. An error somewhere deep inside the SQLalchemy library.
So next, I tried just skipping sqlautocode and writing the classes and relations myself, going by this code for SQLalchemy 0.8. I used two example tables and I got the exact same error. Then I commented out most of the columns, all of the relations and I -STILL- get the error.
Below is my code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.dialects.mssql import *
Base = declarative_base()
class PeopleMemberhip(Base):
__tablename__ = 'people_memberships'
ppl_mshp_id = Column(VARCHAR(length=36), primary_key=True, nullable=False)
ppl_mshp_startdate = Column(DATETIME())
ppl_mshp_enddate = Column(DATETIME())
# ppl_mshp_pmsd_id = Column(VARCHAR(length=36), ForeignKey('paymentschedules.pmsd_id'))
# paymentschedule = relationship("PaymentSchedule", backref=backref('people_memberships'))
def __repr__(self):
return "<people_membership('%s','%s')>" % (self.ppl_mshp_id, self.ppl_mshp_startdate)
class PaymentSchedule(Base):
__tablename__ = 'paymentschedules'
pmsd_id = Column(VARCHAR(length=36), primary_key=True, nullable=False)
pmsd_name = Column(NVARCHAR(length=60))
pmsd_startdate = Column(DATETIME())
pmsd_enddate = Column(DATETIME())
# paymentschedule = relationship("PaymentSchedule", backref=backref('people_memberships'))
def __repr__(self):
return "<paymentschedule('%s','%s')>" % (self.pmsd_id, self.pmsd_name)
And the resulting Error:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm 2.7\helpers\pydev\pydevd.py", line 1472, in <module>
debugger.run(setup['file'], None, None)
File "C:\Program Files (x86)\JetBrains\PyCharm 2.7\helpers\pydev\pydevd.py", line 1116, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "C:/Users/erik/workspace/flasktest/test.py", line 16, in <module>
contract = db.session.query(PeopleMemberhip).filter_by(ppl_mshp_id='98ABD7E9-4CFF-4F7B-8537-8E46FD5C79D5').one()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\session.py", line 1105, in query
return self._query_cls(entities, self, **kwargs)
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 115, in __init__
self._set_entities(entities)
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 124, in _set_entities
self._set_entity_selectables(self._entities)
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 157, in _set_entity_selectables
ent.setup_entity(*d[entity])
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 2744, in setup_entity
self._with_polymorphic = ext_info.with_polymorphic_mappers
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\util\langhelpers.py", line 582, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\mapper.py", line 1425, in _with_polymorphic_mappers
configure_mappers()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\mapper.py", line 2106, in configure_mappers
mapper._post_configure_properties()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\mapper.py", line 1242, in _post_configure_properties
prop.init()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\interfaces.py", line 231, in init
self.do_init()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\properties.py", line 1028, in do_init
self._setup_join_conditions()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\properties.py", line 1102, in _setup_join_conditions
can_be_synced_fn=self._columns_are_mapped
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\relationships.py", line 115, in __init__
self._annotate_fks()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\relationships.py", line 311, in _annotate_fks
self._annotate_present_fks()
File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\relationships.py", line 331, in _annotate_present_fks
secondarycols = util.column_set(self.secondary.c)
AttributeError: 'RelationshipProperty' object has no attribute 'c'
I'm really at a loss, any help with this error is appreciated, but also if someone can suggest a different approach that can make SQLalchemy work with our legacy MSSQL database it is also a solution.
As I said, sqlautocode doesn't seem to work any more, but maybe I'm using it the wrong way, or maybe there is an alternative tool I don't know about.
Erik
Okay guys, figured it out myself.
I had a couple of files I was messing with that had table definitions in them (output from sqlautocode). One was called 'database.py' another 'model.py' and the last one 'ORM.py'.
I had a test.py file that imported 'model.py'. Model.py was the file I had written my table definitions in. However - the test.py page was also importing the database from within Flask (from app import app, db), and in the __init__() function of the Flask app, Flask was still loading 'ORM.py'.
So some of the objects were coming from ORM.py, which was an old file generated by sqlautocode, instead of from model.py, which I was experimenting with.
Renaming ORM.py gave me a clue. I have written a very simple script in Python that traverses through the MSSQL tables and columns and generates a model.py for me. I exclusively load that model.py file now and the whole thing works!
Sorry if anyone was spending time on this. Hope it helps somebody Googleing for the same problem though.
Erik

Categories