Sunday, October 3, 2010

Any way to select which Model to initialize without resorting to "if-elfi" statements?

I need to model many different product categories such as TV, laptops,
women's apparel, men's shoes, etc.

Since different product categories have different product attributes,
each category has its own separate Model: TV, Laptop, WomensApparel,
MensShoes, etc.

And for each Model I created a ModelForm. Hence I have TVForm,
LaptopForm, WomensApparelForm, MensShoesForm, etc.

Users can enter product details by selecting a product category
through multi-level drop-down boxes. Once a user has selected a
product category, I need to display the corresponding product form.

The obvious way to do this is to use a giant `if-elif` structure:

# category is the product category selected by the user
if category == "TV":
form = TVForm()
elif category == "Laptop":
form = LaptopForm()
elif category == "WomensApparel":
form = WomensApparelForm()
...

Unfortunately there could be hundreds if not more of categories. So
the above method is going to be error-prone and tedious.

Is there any way I could use the value of the variable `category` to
directly select and initialize the appropriate `ModelForm` without
resorting to a giant `if-elif` statement?

Something like:

# This doesn't work
model_form_name = category + "Form"
form = model_form_name()

Is there any way to do this?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment