paulocheque / django-dynamic-fixture

A complete library to create dynamic model instances for testing purposes.
http://django-dynamic-fixture.readthedocs.io/
Other
390 stars 67 forks source link

Add support for string as model name in G, N #92

Closed theskumar closed 4 years ago

theskumar commented 6 years ago

I'm using this monkey patched version of G that accepts app_name.ClassName string format similar to how you would use in models.ForeignKey().

from django_dynamic_fixture import G as __G

def G(model, **kwargs):
    """Overrides the G to be able to use it with 'app_name.model_name'
    format as well.

    >>> G('users.User', email="mail@examle.com")
    <User: mail@examle.com>
    >>> G(User, email="mail@example.com")
    <User: mail@examle.com>
    """

    if isinstance(model, str):
        from django.apps import apps
        model = apps.get_model(model)
    return __G(model, **kwargs)

I think it would be a nice backward-compatible add-on to the library itself. @paulocheque thoughts? I'll submit a PR.

paulocheque commented 6 years ago

When it is useful to use the string for you? To avoid importing?

I guess it could be useful for some situation really. Is that compatible with all Django versions? You could also move the import to outside the function. Also, could you include some docs update in the PR?

Awesome!

theskumar commented 6 years ago

This is useful as I don't have to keep on importing a model class, while writing tests. In the tests, I generally don't need the model class but the instance of a model.

The support for apps.get_model() is from Django>=1.7, and the last officially supported django right now is 1.8.

I'll include docs update. :)

paulocheque commented 4 years ago

Thanks again @theskumar !

I created the PR for that awesome idea: https://github.com/paulocheque/django-dynamic-fixture/pull/104