Thierry Lam
Thierry Lam

Reputation: 46264

How can I store many Django model types in a database and access them as an object?

I have the following Django models:

Bar, Bistro and Restaurant

Each of the above establishment has their own menu items, for instance:

  1. Bar
    • Burger
    • Fries
    • ...
  2. Bistro
    • Pasta
    • Pizza
    • ...
  3. Restaurant
    • Duck
    • Wings
    • ...

I have different type of images in my home page, a main banner, left side bar and right side bar. Each of those images will have links to menu items across the Bar, Bistro and Restaurant. I'm currently hard-coding the urls for each of those images in the admin:

class Image(models.Model):
    alt_name = models.CharField
    source = models.ImageField
    url = models.CharField

The above is working fine but if one of the menu item changes, I will have to go back to the admin and re-write the new url. I'm thinking of improving my admin to make it look like the following:

alt text

Selecting the appropriate establishment will populate the proper menu items. In the backend, the database will store a string corresponding to the type of establishment along with a primary key of a menu item related to that establishment. I need the establishment association because the menu items are stored in their own tables(BarMenuItem, BistroMenuItem and RestaurantMenuItem).

Given a string Bistro, is it possible to retrieve its corresponding model of the same name in Django? I believe I might have gone overboard with the above solution, let me know of your thoughts if you have any suggestions.

Upvotes: 1

Views: 291

Answers (1)

cethegeek
cethegeek

Reputation: 6394

Given a string Bistro, is it possible to retrieve its corresponding model of the same name in Django?

Yes.

model = ContentType.objects.get(model='Bistro').model_class()

http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/

Upvotes: 1

Related Questions