是否可以在具有ManyToMany关系的Django中将管理表单用于代理模型?

时间:2018-11-07 17:18:42

标签: django django-models django-forms django-admin

我正在对测验和相关问题进行建模,如下所示:

# models
class Question(models.Model):
    title = models.TextField()
    category = models.TextField()


class Quiz(models.Model):
    questions = models.ManyToManyField(Question, through='OrderedQuestion')


class OrderedQuestion(models.Model):
    # A through table to allow ordering of questions
    question = models.ForeignKey(Question, ...)
    quiz = models.ForeignKey(Quiz, ...)
    order = models.PositiveIntegerField(default=0)

我有两种由代理模型处理的问题:

# proxy models to handle specific question categories
class BoatQuestion(Question):
     objects = BoatQuestionManager()  # handles setting category

     class Meta:
         proxy = True

CarQuestion的相似名称。

我对BoatQuestionsCarQuestions都有内联,以便可以在Quiz管理页面上对其进行独立编辑。管理员设置为:

class QuestionAdmin(admin.ModelAdmin):
    model = Question


class BoatQuestionAdmin(admin.ModelAdmin):
    model = BoatQuestion


class CarQuestionAdmin(admin.ModelAdmin):
    model = CarQuestion


class BoatQuestionInline(admin.TabularInline):
    model = BoatQuestion.quiz.through

    def get_queryset(self, *args, **kwargs):
        return OrderedQuestion.objects.filter(question__category='boat')

    def formfield_for_foreignkey(self, *args, **kwargs):
        if db_field.name == 'question':
            kwargs['queryset'] = BoatQuestion.objects.all()
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


class CarQuestionInline(admin.TabularInline):
    # similar to above


class QuizAdmin(admin.ModelAdmin):
    model = Quiz
    inlines = (BoatQuestionInline, CarQuestionInline)

BoatQuestionsCarQuestions的添加和编辑按钮使用Question的通用管理表单。有没有办法确保在内联编辑BoatQuestionAdmin时使用BoatQuestions表单?

0 个答案:

没有答案