[英]Creating a model in Django whose field has multiple other fields inside it
[英]Django, creating multiple identical fields in the same model
我对 Django 完全陌生,所以如果这是错误的方法,请原谅我。 在我尝试学习 Django 的同时,我喜欢做自己的小练习题来巩固我的理解。
使用模型我创建了示例 model 对象:
from django.db import models
class Food(models.Model):
name = models.CharField(
max_length=50,
help_text="Name of Fruit or Vegetable"
)
food_group = models.CharField(
max_length=9,
class Vitamins(models.Model):
name = models.ForeignKey(
Food,
on_delete=models.CASCADE
)
vitamin_A = models.CharField(
max_length=20,
)
.
.
.
folate = models.CharField(
max_length=20,
help_text="Folic Acid"
)
在我的 object 中,我有 5 个相同的字段来存储文本,即(微量、5mg、无信息)。 但是,输入每个字段似乎很乏味。 有没有更有效的方法来做到这一点?
我认为您应该利用关系数据库并为维生素创建一个 model,名称和叶酸,类似这样
from django.db import models
class Food(models.Model):
name = models.CharField(
max_length=50,
help_text="Name of Fruit or Vegetable"
)
class Vitamin(models.Model):
food = models.ForeignKey(
Food,
on_delete=models.CASCADE
)
name = models.CharField(
max_length=20,
)
folate = models.CharField(
max_length=20,
help_text="Folic Acid"
)
然后为食物中的每一种维生素创造一个记录。 它可以是 1、2 或 N。这是非常灵活和可扩展的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.