我希望能够从LANGUAGES中添加和删除项目,而不是像这样对它们进行硬编码。现在我得到了我需要的东西,它是Dropdown,具有“ English”,“ German”和“ Italian”选项。现在,我需要将它们放在SQLite数据库中并从那里检索,并可以选择添加新语言并删除/编辑现有语言。提前致谢...
LANGUAGES = [
("1", "English"),
("2", "German"),
("3", "Italian"),
]
language = models.CharField(max_length=50, choices=LANGUAGES, default=1, null=False)
You do that with a
ForeignKey
[Django-doc], For example:You can then populate the database with records for
Language
, and select the language for theMyModel
objects.If you use a
ModelForm
, then standard Django will make a dropdown with the options in the "target" model (and usestr(…)
to represent these objects).It is probably better to set
unique=True
[Django-doc] for thename
field, to prevent creating anotherLanguage
object with the same name.By setting
on_delete=models.PROTECT
we prevent removing a language, givenMyModel
refers with at least one object to that language. So you can only remove languages if noMyModel
is referring to it anymore.The database will normally guarantee referential integrity. That means that the
language
column stores the value of the primary key of the object it refers to. The database normally guarantees that if one such column contains a value x, then there is a primary key with that value in the table forLanguage
.如果要以表单形式执行此操作,请为语言创建一个新模型并填充表格。