【发布时间】:2021-01-17 20:13:28
【问题描述】:
我对编程、Django 和创建应用程序还比较陌生,所以请多多包涵。我正在开发一个饮食应用程序,我很难想象和理解为什么我的一个模型的ManyToManyField 的特定用例没有出现在管理控制台中。我尝试阅读 Django 文档以了解 ManyToManyField 关系,但我仍然无法理解它,所以希望有人能像我是一只快乐的金毛猎犬一样向我解释这一点。
我有三个模型:
class Product(models.Model):
product_name = models.CharField(verbose_name='Product name', max_length=100)
product_description = models.TextField(verbose_name='Product description', max_length=500)
product_id = models.UUIDField(default=uuid.uuid4(), unique=True)
def __str__(self):
return self.product_name
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
class Recipe(models.Model):
recipe_name = models.CharField(verbose_name='Recipe name', max_length=100)
ingredients = models.ManyToManyField(Product, related_name='Ingredients', through='IngredientQuantity', through_fields=('recipe','ingredient'))
class Meta:
ordering = ['recipe_name']
def __str__(self):
return self.recipe_name
#-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------#
class IngredientQuantity(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.DecimalField(verbose_name='Quantity', decimal_places=2, max_digits=99, null=False)
我试图用IngredientQuantity 创建一个中介,它会给我数量以及选定的Product,然后我可以将其与Recipe 关联。
但是,当我尝试在 Django 管理控制台中为 Recipe 创建一个新条目时,我没有看到 Recipe 的 ingredients 输入,这应该是这种情况吗?
【问题讨论】:
标签: python django database django-models