Django admin中的编辑被外键反转

wfveoks0  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(148)

如何在类QuestionsAdmin(admin.ModelAdmin)中实现Django中的管理员在Question中可以查看所有,添加,编辑和删除所有Answers?

class Answer(models.Model):
  id = models.UUIDField(primary_key=True, default=uuid4)
  value = models.TextField()
  correct = models.BooleanField()
  question = models.ForeignKey("Questions", models.DO_NOTHING)

class Question(models.Model):
  id = models.UUIDField(primary_key=True, default=uuid4)
  content = models.TextField()
vwoqyblh

vwoqyblh1#

在ModelAdmin中使用内联
在admin.py

from django.contrib.admin import StackedInline

class AnswerInline(StackedInline):
    model = Answer
    extra = 0
    verbose_name = "Answer"
    verbose_name_plural = "Answers"

class QuestionAdmin(admin.ModelAdmin):
    inlines = [AnswerInline]

admin.site.register(Question, QuestionAdmin)

您也可以使用TabularInline来代替StackedInline,具体取决于样式。

相关问题