j hanover
j hanover

Reputation: 1

How can I establish grouping in Django through models?

I created a model named MenuItems which will allow for me to enter all of the items that a restaurant has on their menu, later I will use these on the front end. I also created a model name MenuGrouping so that on the front end, I can have Bootstrap tabs show the group_title and under each, show the items in that group. What field should I add in the MenuItems model to associate it to a group? I attempted to use group = models.ForeignKey(MenuGrouping) but then I run into the issue of showing each item in the specific group.

Models.py:

class MenuItems(models.Model):

  menu_item_title = models.CharField(max_length=256)
  menu_item_description = models.TextField()
  menu_item_price = models.DecimalField(max_digits=4, decimal_places=2)

  customer_favorite = models.BooleanField(default=False)
  is_on_menu = models.BooleanField(default=True)

class Meta:
    ordering = ('menu_item_title', )


class MenuGrouping(models.Model):
    group_title = models.CharField(max_length=256)

Is there a relationship that I can add in the MenuGrouping model that I can associate multiple MenuItems?

Thank you in advance!

Upvotes: 0

Views: 51

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

If I understand you correctly that you are trying to make groups like drink, food, desert and ... then here it is:

Each item can be only in one group (I mean soda is a drink and it can't be food too and etc). So what you need to do here is to add a field to MenuItems model.

your MenuItems should be like this:

class MenuItems(models.Model):

    menu_item_title = models.CharField(max_length=256)
    menu_item_description = models.TextField()
    menu_item_price = models.DecimalField(max_digits=4, decimal_places=2)

   customer_favorite = models.BooleanField(default=False)
   is_on_menu = models.BooleanField(default=True)
   group = models.ForeignKey(MenuGrouping)

Now to use this in your template first get the groups in view and send them to template and then:

{% for group in groups %)

    # add your tabs or just print the group name. or how ever you want.

    Group {{ group.group_title }}:

    # and now you can list the items in this group here

    {% for item in group.menuitems_set.all %}
        Title is: {{ item.menu_item_title }}
        Price is: {{ item.menu_item_price }}
        ...
    {% endfor %}
{% endfor %}

If you need all items to be listed somewhere else out of groups or any other way just send the items to the template too.

Here is the Many to One relationship documentation : Many-to-one relationships

Also you can add a m2m relation to MenuGrouping and add items to each group but then one item can be in multiple groups and for a restaurant menu I can't see how that might happen.

Upvotes: 1

Related Questions