django - Making list of model into field of another model in django
问题描述
I am totally newbie in django and I am trying to make a restaurant app. I have two models: component and meal, and i want to make a field in meal model that contains a list of components models. Is there any way to do such a thing ? For example sandwich contains bread, cheese and ham. Thanks for your help
解决方案
在这种情况下,您应该使用ManyToMany。你的模型应该是这样的:
class Component(models.Model):
name = models.CharField(max_length=255)
# other fields
class Mean(models.Model):
components = models.ManyToManyField(Component)
用法:
meal = Mean.objects.create(name = "Sandwich")
bread = Componrnt.objects.create(name='Bread')
mean.components.add(bread)
推荐阅读
- java - 使用spring boot时如何在apache camel spring xml路由中给出端点标签
- python - Pandas DataFrame 到 Latex 格式化程序函数
- javascript - 将对象追加/添加/取消移动到来自 api 的响应的开头
- elasticsearch - query_string 中的通配符搜索
- sql-server - 根据文件日期获取 SQL Server 中的先前记录
- c++ - 如何从操作“newaccount”中获取 EOS 公钥
- laravel - 如何使用带有 Lighthouse 参数的自定义 Laravel 规则
- c# - 以编程方式从项目资源安装内置字体,C# winforms
- firebase - Firebase 动态链接查询参数始终为空
- javascript - 使用 JavaScript 从表格单元格中提取数据