Django models defined in tests.py are not created in database

I am trying to run on of test suit given by Django git hub


on default database sqlite.

For this apps “custom_lookups” I get an error saying “Exception: Statement Execute Failed: [IBM][CLI Driver][DB2/NT64] SQL0204N “DB2ADMIN.CUSTOM_LOOKUPS_CUSTOMMODEL” is an undefined name. SQLSTATE=42704”

I am using this command “./runtests.py --settings=settings custom_lookups” I also included this app name in INSTALLED_APPS under settings file.

This model (i.e custommodel) for which I am getting error is defined in tests.py as below,


class CustomField(models.TextField):

def get_lookup(self, lookup_name):
if lookup_name.startswith(‘lookupfunc_’):
key, name = lookup_name.split(’_’, 1)
return SQLFuncFactory(key, name)
return super().get_lookup(lookup_name)

def get_transform(self, lookup_name):
if lookup_name.startswith(‘transformfunc_’):
key, name = lookup_name.split(’_’, 1)
return SQLFuncFactory(key, name)
return super().get_transform(lookup_name)

class CustomModel(models.Model): field = CustomField()


What I found is models defined in models.py file is been migrated but any models defined in tests.py is not migrated but would got created during running test case and get deleted at same time once test case is run.

My question is why models defined in tests.py are not picked for migration but after running complete test suite its trying to flush this ? hence I get above said error.

whats fix for this ?

One of same issue reported I found here https://github.com/jazzband/django-nose/issues/15 but I didnt get any solution.

Models are only discovered for migrations if they are in, or imported from, a models.py file inside one of your apps. If you define models inside your tests, they won’t get database tables created for them.

(also, I moved this to Using Django, as that’s the right forum for questions about using Django)

@andrewgodwin What you said is correct, models defined in models.py will be discovered for migrations. And also after migrations it should flush only the tables which are migrated. In my case models which I defined in tests.py is not considered for migrations (which is expected) but they are considered for flushing (which is not supposed to) hence I get an error. Not sure how to ignore these models defined in tests.py for flushing.