python - Django - 向用户询问每个菜单项的菜单项选择
问题描述
我正在用 django 和 mysql 开发一个简单的餐厅应用程序,经过几天的谷歌搜索和研究,我无法为这个特定问题找到合适的答案,这是我的 django 模型
class MenuItem(models.Model):
menu_category = models.ForeignKey(MenuCategory, to_field='slug', on_delete=models.CASCADE)
name = models.CharField(max_length=30)
image = models.ImageField(upload_to='uploads/menu/')
slug = models.SlugField(null=True, blank=True, unique=True)
price = models.DecimalField(max_digits=9, decimal_places=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
这就是问题所在:例如,我有一个菜单项“墨西哥汉堡”,我想问用户他们选择的肉……即鸡肉或牛肉,或者他们选择的面包,白色或棕色,
或者我可能有一个 MenuItem “OMELETTE COMBO”,我想询问用户他们想要的煎蛋类型,例如(“西班牙煎蛋”、“菠菜和蘑菇煎蛋”)
或者我可能有一个 MenuItem “ESPRESSO”,我希望他们在('single','double')之间进行选择
*一个菜单项可以有多个与之相关的选择,即汉堡项目可以选择面包和肉类,以便更好地了解我的问题,请访问此 链接 *和此另一个链接
解决方案
对此有不同的解决方案。
基于代码:继承
您为每个选择类型和子类 MenuItem 和这些混合创建混合。
from django.db.models import CharField, TextChoices, Model
class MeatChoices(TextChoices):
CHICKEN = 'chi'
BEEF = 'bee'
class MeatMixin(Model):
meat_choices = CharField(max_length=3, choices=MeatChoices.choices, default=MeatChoices.CHICKEN)
class MeatMenuItem(MeatMixin, MenuItem):
pass
每当向菜单添加更多选项或在这方面更改菜单时,这将需要更改代码。
基于数据:通用模型
要允许管理员用户通过 Django Admin 创建菜单项并将其添加到菜单项中,您需要创建一个模型结构来启用指定选项:
from django.contrib.postgres.fields import ArrayField
from django.db.models import ManyToManyField, CharField, Model
class Ingredient(Model):
name = CharField(max_length=50, unique=True)
class IngredientChoiceGroup(Model):
name = CharField(max_length=50, unique=True)
# simple solution for postgres only:
# ingredients = ArrayField(CharField(max_length=50))
# if not postgres or you need more attributes to ingredient:
ingredients = ManyToManyField(Ingredient)
class MenuItem(models.Model):
menu_category = models.ForeignKey(MenuCategory, to_field='slug', on_delete=models.CASCADE)
name = models.CharField(max_length=30)
image = models.ImageField(upload_to='uploads/menu/')
slug = models.SlugField(null=True, blank=True, unique=True)
price = models.DecimalField(max_digits=9, decimal_places=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
ingredient_choices = ManyToManyField(IngredientChoiceGroup)
def __str__(self):
return self.name
此方法将允许为每个菜单项配置多个选择组,例如“面包”和“肉类”。你可以通过 Django Admin 来完成这一切。
你可能需要弄清楚细节。这只是一个草稿。
注意ArrayField
:它是数据库中更简单的结构,但对于管理员,您需要通过 3rd 方库添加特定的小部件,或者至少编写自己的解析器。最后,M2M 领域可能是更好的选择。
推荐阅读
- javascript - 如果对象包含某些东西,js删除所有数组元素
- vue.js - b-form-input 如何在 bootstrap-vue 表格单元格中使用@blur 修改/格式化输入?
- sql - 一行中的多行由多列逗号分隔
- node.js - 在启用严格模式的 TypeScript 中扩展实例(原型)
- webpack - 如何在不捆绑的情况下使用 webpack 缩小文件
- docker - 测试泊坞窗图像。使用 exec 轻松启动并获取日志
- javascript - 如何在 Mocha 中使用增量变量创建测试名称
- sms - 如何在 Windows 10 中安装 Jasmin 短信网关
- apache - 在 htaccess 中重定向到真实页面
- python - 如何从框架中删除所有标签但保留菜单/按钮?tkinter,蟒蛇