简体   繁体   中英

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:

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

I'm not sure how to approach this problem.

I think I achieved what I wanted partially:

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:

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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