Craig Otis
Craig Otis

Reputation: 32054

Store multiple instances of same item in Django ManyToMany relationship

I have a Django model representing a simple grocery list, as follows (truncated for brevity)

class Meal(models.Model):
    name = models.CharField(max_length = 200)
    ingredients = models.ManyToManyField(Ingredient)

class GroceryList(models.Model):
    name = models.CharField(max_length = 200)
    meals = models.ManyToManyField(Meal)
    ingredients = models.ManyToManyField(Ingredient)

This allows a GroceryList to contain both Meal objects, and Ingredient objects. (This way a list can group ingredients together when they're needed for a Meal.)

The problem is, I want a GroceryList to be able to contain the same Meal twice, or more. What's the most efficient solution?

I had considered wrapping the Meal class in an object ('MealContainer') that maintained both the underlying Meal, alongside a quantity, but that seems a little heavy-handed.

Upvotes: 0

Views: 636

Answers (2)

rkyser
rkyser

Reputation: 3357

I don't know if this is the most efficient way, but you could break down your list of meals into daily menus. That's typically how my wife plans our grocery list.

class Meal(models.Model):
    MEAL_TYPE = (
        (u'B','Breakfast'),
        (u'2','Second Breakfast'),
        (u'E','Elevenses'),
        (u'L','Luncheon'),
        (u'A','Afternoon Tea'),
        (u'D','Dinner'),
        (u'S','Supper'),
    )
    name = models.CharField(max_length = 200)
    ingredients = models.ManyToManyField(Ingredient)
    meal_type = models.CharField(max_length=2, choices=MEAL_TYPE)

class DailyMenu(models.Model):
    date = models.DateField()
    meal = models.ManyToManyField(Meal)

class GroceryList(models.Model):
    name = models.CharField(max_length = 200)
    meal_menus = models.ManyToManyField(DailyMenu)
    ingredients = models.ManyToManyField(Ingredient)

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599630

Perhaps consider a through model with a quantity field.

Upvotes: 3

Related Questions