berinhard / model_mommy

No longer maintained, please migrate to model_bakery
http://model-bakery.readthedocs.org/
Other
903 stars 141 forks source link

Use class inheritance to detect appropriate generator. #108

Closed mrmachine closed 10 years ago

mrmachine commented 11 years ago

I have many custom field types, most are subclass of Django's standard field types with some small modification (strip white space, use a different default form widget, etc.)

Trying to use model_mommy, first thing I get is an exception about my field type not being supported. So I check the docs and find I need to define a mapping for each custom field to a generator in my settings file.

Since my fields are mostly subclass of standard Django fields, I think I should be able to map my field to the built in model_mommy generators. I try:

from model_mommy import generators
MOMMY_CUSTOM_FIELDS_GEN = {
    'turbia.models.CharField': generators.gen_string,
}

But importing generators from inside my settings file gives me a surprising error about:

ImproperlyConfigured: The SECRET_KEY setting must not be empty.

I guess there's a circular import because generators does:

from django.contrib.contenttypes.models import ContentType
from django.db.models import get_models

model_mommy could fix this by moving these imports into the gen_content_type() function, but I'd still need to define a mapping for every custom field.

Couldn't model mommy use isinstance() or issubclass() for each generator and pass a list of compatible Django fields instead of an explicit mapping? This should work for subclasses. Perhaps this could be a fallback, in addition to an explicit mapping if there is still a need for that.

berinhard commented 11 years ago

@mrmachine the problem on your approach is that you're trying to import on settings something from model mommy. The problem with this is that model mommy depends o Django settings, so, when model mommy tries to import the settings during your import on your settings.py, the django settings is not well configured, so it raises the error... The correct way to do this is to import for a common python module that has no dependency on Django settings. I don't know if I made myself clear...

mrmachine commented 11 years ago

Yes, that is the problem that I already described, and which I have resolved with the pull request above by removing the requirement for model mommy to import Django settings at the module level.