[英]Django, creating multiple identical fields in the same model
I am completely new to Django, so forgive me if this is the wrong approach.我对 Django 完全陌生,所以如果这是错误的方法,请原谅我。 While I'm trying to learn Django, I like to do my own little practice problems to solidify my understanding.
在我尝试学习 Django 的同时,我喜欢做自己的小练习题来巩固我的理解。
Working with models I created the example model objects:使用模型我创建了示例 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"
)
In my object, I have 5 identical fields that store text ie (Trace amounts, 5mg, No Information).在我的 object 中,我有 5 个相同的字段来存储文本,即(微量、5mg、无信息)。 However it seems tedious to type out every field.
但是,输入每个字段似乎很乏味。 Is there a more efficient way to do this?
有没有更有效的方法来做到这一点?
I think you should take advantage of the relational database and create a model for Vitamin, with name and folate, something like this我认为您应该利用关系数据库并为维生素创建一个 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"
)
And then for every Vitamin in the Food you create a record.然后为食物中的每一种维生素创造一个记录。 It can be 1, 2 or N. This is very flexible and scaleable.
它可以是 1、2 或 N。这是非常灵活和可扩展的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.