简体   繁体   English

在管理页面上为Django模型创建双向ManyToMany关系

[英]Creating a Bidirectional ManyToMany Relationship for Django Models on Admin Page

I'm using the Django tutorial for 1.8 & Python 3.4 and right now the page has Questions that can add multiple Choices, but Choices cannot access its corresponding Question: 我正在使用适用于1.8和Python 3.4的Django教程,现在该页面上的Questions可以添加多个Choices,但是Choices无法访问其相应的Question:

#models.py
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

class Choice(models.Model):
    question = models.ForeignKey('Question')
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text
#admin.py
from django.contrib import admin

from .models import Question, Choice

# Register your models here.

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

# class QuestionInline(admin.TabularInline):
#     model = Question.choice.through
#     extra = 3

class QuestionAdmin(admin.ModelAdmin):
    # fieldsets = [   (None, {'fields': ['question_text']}),
    #                 ('Date information', {'fields': ['pub_date'],'classes':
    #                 ['collapse']})
    #             ]
    list_display = ('question_text', 'pub_date', 'was_published_recently')
    list_filter = ['pub_date']
    search_fields = ['question_text']
    inlines = [ChoiceInline]

class ChoiceAdmin(admin.ModelAdmin):
    fields = ['choice_text', 'votes']

    #inlines = [QuestionInline]

admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice, ChoiceAdmin)

However, I want to be able to have the Questions have many Choices and be able to access those Choices in admin and then Choices have access to their corresponding Question in the admin page as well. 但是,我希望问题可以有很多选择,并能够在管理员中访问这些选择,然后选择也可以在管理页面中访问其相应的问题。

I was thinking of creating a ManyToMany variable for the Choice, but that seems to remove the capability of having TabularInline Editing which requires a Foreign Key. 我当时正在考虑为Choice创建一个ManyToMany变量,但这似乎消除了具有TabularInline Editing(需要外键)的功能。

I'm not sure how to approach this problem. 我不确定如何解决这个问题。

I think I achieved what I wanted partially: 我想我部分实现了自己想要的目标:

models.py: models.py:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

class Choice(models.Model):
    #question = models.ForeignKey('Question')
    related_question = models.ManyToManyField(Question, related_name='questions')
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

class Related(models.Model):
    question = models.ForeignKey(Question)
    choice = models.ForeignKey(Choice)

admin.py: admin.py:

class RelatedInline(admin.TabularInline):
    model = Related
    extra = 1


class QuestionAdmin(admin.ModelAdmin):
    # fieldsets = [   (None, {'fields': ['question_text']}),
    #                 ('Date information', {'fields': ['pub_date'],'classes':
    #                 ['collapse']})
    #             ]
    #list_display = ('question_text', 'pub_date', 'was_published_recently')
    #list_filter = ['pub_date']
    #search_fields = ['question_text']
    #inlines = [ChoiceInline]
    inlines = (RelatedInline,)

class ChoiceAdmin(admin.ModelAdmin):
    #fields = ['choice_text', 'votes']
    #filter_horizontal = ('related_question',)
    #list_display = ('question',)
    #list_display_links = ('question',)
    #inlines = [QuestionInline]
    #list_filter = ('related_question', admin.RelatedOnlyFieldListFilter)
    inlines = (RelatedInline,)
    exclude = ('related_question',)
admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice, ChoiceAdmin

)

And this made it so I could add related choices to questions and questions to choices. 这样就可以将相关的选择添加到问题中,并将问题添加到选择中。

However I was also wondering if there was a way to edit the Choice model while inside the Question model? 但是,我还想知道在Question模型内部是否可以编辑Choice模型? Or link directly to the model itself when selecting that particular choice. 或在选择特定选项时直接链接到模型本身。

source: https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#working-with-many-to-many-intermediary-models 来源: https : //docs.djangoproject.com/en/1.8/ref/contrib/admin/#working-with-many-to-many-intermediary-models

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

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