[Django]-How can I dynamically create objects in django/python?

7👍

The simplest translation is:

types = dict('cat' = CatType, 'dog' = DogType)
newobj = types[type](user = user, cat_id = thing_id)

Obviously, this relies on the types taking the same parameters.

👤Marcin

3👍

Classes in Python are objects, so you can just have a map mapping names to classes:

animal_type_map = {'cat': VoteCat, 'dog': VoteDog}

Then you can use animal_type_map[type] just as you would use VoteCat or VoteDog.

Leave a comment