简体   繁体   English

是否可以在同一管理页面上对同一模型具有两个ManyToMany关系?

[英]Is it possible to have two ManyToMany relationships to the same model on the same admin page?

I modelling a quiz and the associated questions as follows: 我对测验和相关问题进行建模,如下所示:

# 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)

I have two types of questions that are handled by proxy models: 我有两种由代理模型处理的问题:

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

     class Meta:
         proxy = True

and a similar one for CarQuestion . 还有一个类似的CarQuestion

I want to be able to edit BoatQuestions and CarQuestions independently from each other but on the same admin page. 我希望能够在同一管理页面上彼此独立地编辑BoatQuestionsCarQuestions The admin setup is: 管理员设置为:

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


class CarQuestionInline(admin.TabularInline):
    model = CarQuestion.quiz.through


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

but whenever I change the questions in the boat question section, the questions in the car section update to match it and vice versa. 但是只要我更改了“船用问题”部分中的问题,“汽车”部分中的问题就会更新以匹配它,反之亦然。

Is there any way to show these on the same admin page but change them independently? 有什么方法可以在同一管理页面上显示这些信息,但可以独立更改吗?

The problem lies in your inlines. 问题出在你的内联上。 You use the same model for both, which is fine. 两者都使用相同的模型,这很好。 But as you want to show only certain Question s, you have to adjust the QuerySet for each inline and add an appropriate .filter() . 但是,由于只想显示某些Question ,因此必须为每个内联调整QuerySet并添加适当的.filter() (I am guessing here, how you distinguish the category of the questions.) (我在这里猜测,您如何区分问题的类别。)

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

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


class CarQuestionInline(admin.TabularInline):
    model = CarQuestion.quiz.through

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM