[Answer]-Django passing object to class

1👍

You can make classes on the fly:

def foo(column):
    class Foo(object):
        if column == 'a':
            bar = 'a'
            foo = 'c'
        else:
            bar = 'b'

    return Foo

for x in 'ab':
    cls = foo(x)
    print cls.bar
    print cls.foo

There are other ways to do this, look up info on metaclasses. Here is a really good lecture on the subject.

In your case I’d do:

def import_data(column, *args, **kw):
    # make custom ContactCSVModel
    class ContactCSVModel(CsvModel):
        # IF column == x

        first_name = CharField()
        last_name = CharField()
        company = CharField()
        mobile = CharField()
        group = DjangoModelField(Group)
        contact_owner = DjangoModelField(User)

        class Meta:
            delimiter = ","
            dbModel = Contact
            update = {'keys': ["mobile", "group"]}

    return ContactCSVModel.import_data(*args, **kw)

# in another file, you can even mask it as your model class,
# I wouldn't do that however
import somemodule as ContactCSVModel

# Try and import CSV
ContactCSVModel.import_data(form, data=file, extra_fields=[
                           {'value': upload.group_id, 'position': 5},
                           {'value': upload.uploaded_by.id, 'position': 6}])


# or you could make a function that returns a class
def contact_model(column):
    # make class
    return ContactModel

# then
from somemodule import contact_model

ContactCSVModel = contact_model(column=form)

# then use as normally
ContactCSVModel.import_data(data=file, extra_fields=[
                           {'value': upload.group_id, 'position': 5},
                           {'value': upload.uploaded_by.id, 'position': 6}])
👤gatto

Leave a comment