从数据库中的数据填充下拉列表-Django

我希望能够从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:

class Language(models.Model):
    name = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.name

class MyModel(models.Model):
    language = models.ForeignKey(Language, on_delete=models.PROTECT)

You can then populate the database with records for Language, and select the language for the MyModel objects.

If you use a ModelForm, then standard Django will make a dropdown with the options in the "target" model (and use str(…) to represent these objects).

It is probably better to set unique=True [Django-doc] for the name field, to prevent creating another Language object with the same name.

By setting on_delete=models.PROTECT we prevent removing a language, given MyModel refers with at least one object to that language. So you can only remove languages if no MyModel 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 for Language.

点赞
评论
pdolor
pdolor

如果要以表单形式执行此操作,请为语言创建一个新模型并填充表格。

class Language(Model):
    name = models.CharField(max_length=50)

class MyLanguageForm(ModelForm):
    language = forms.ModelChoiceField(queryset=Languages.objects.all())

    # The rest
点赞
评论