首页 > 解决方案 > 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

标签: djangolistdjango-models

解决方案


在这种情况下,您应该使用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)

推荐阅读