Django admin select 来自模型的框选项

Django admin select box options from model

我有语言类别、标签和问题模型。在管理面板中添加问题时,我想 select 类别和 multiselect dropdown/checkbox 中的多个标签 这是我的问题模型:

from django.db import models
from datetime import datetime
from languages.models import Language
from categories.models import Category
from tags.models import Tag


class Question(models.Model):
language = models.ForeignKey(Language, on_delete=models.DO_NOTHING)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
tags = models.CharField(max_length=200, blank=True)

def __str__(self):
    return self.title

如何在 Django 管理面板中实现这一点?

为此,我认为您可以使用 ManyToManyField。像这样:

from django.db import models
from datetime import datetime
from languages.models import Language
from categories.models import Category
from tags.models import Tag


class Question(models.Model):

    language = models.ForeignKey(Language, on_delete=models.DO_NOTHING)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.title