Sunday, October 3, 2010

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

On 10/3/2010 4:04 AM, Andy wrote:
> 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?
>
Let's suppose (just for the moment) all your models are defined in a
single module called "forms". Then the easiest way would be:

model_form_name = category + "Form"
form = getattr(forms, model_form_name)

This will raise an exception if there is no form of the required category.

And if the forms aren't all defined in the same module? The easiest
solution would be to write a forms module like this:

from thismodule import WomensApparelForm, TVForm, CandyForm
from thatmodule import LaptopForm
from theothermodule import CarForm, TruckForm

and so on. All you are doing is juggling namespaces, but as "import
this" reminds us, "namespaces are one honking good idea. Let's do more
of those".

regards
Steve

--
DjangoCon US 2010 September 7-9 http://djangocon.us/

--
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