这样的事情呢?
模型.py
from django.db import models
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext as _
User = get_user_model()
class Venture(models.Model):
name = models.CharField(_('name'), max_length=255)
created = models.DateTimeField(auto_now_add=True, editable=False)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Question(models.Model):
title = models.CharField(_(u'title'), max_length=255)
def __str__(self):
return self.title
class VentureQuestion(models.Model):
venture = models.ForeignKey('Venture', related_name='questions')
question = models.ForeignKey('Question', related_name='venture_questions')
def __str__(self):
return "{}: {}".format(self.venture, self.question)
class Answer(models.Model):
question = models.ForeignKey('VentureQuestion', related_name='answers')
responder = models.ForeignKey(User, related_name='answers')
text = models.TextField(_(u'answer'), blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "{}: {}".format(self.responder.username, self.text)
管理员.py
from django.contrib import admin
from example.models import Venture, VentureQuestion, Question, Answer
class AnswerInline(admin.StackedInline):
model = Answer
extra = 0
class VentureQuestionAdmin(admin.ModelAdmin):
inlines = [AnswerInline]
admin.site.register(Venture)
admin.site.register(VentureQuestion, VentureQuestionAdmin)
admin.site.register(Question)
admin.site.register(Answer)
这样,您就可以获得与...Question
相关的每个问题的答案Venture
(听起来这至少是您正在寻找的功能...)
>>> from example.models import Venture
>>> ventures = Venture.objects.all()
>>> for venture in ventures:
... for venture_question in venture.questions.all():
... venture_question.question.title
...
u'What is this?'
u'How does this work?'
u'Does this even work?'
>>> for venture in ventures:
... for venture_question in venture.questions.all():
... venture_question.question.title, [answer.text for answer in venture_question.answers.all()]
...
(u'What is this?', [])
(u'How does this work?', [u'It just does!'])
(u'Does this even work?', [u'Sure it does...', u'I think so'])
你可以有另一个Venture
使用相同Question
但有不同的Answers
>>> venture = Venture.objects.get(name='Another Venture')
>>> for venture_question in venture.questions.all():
... venture_question.question.title, [answer.text for answer in venture_question.answers.all()]
...
(u'What is this?', [])
添加Answer
到新的之后VentureQuestion
>>> venture = Venture.objects.get(name='Another Venture')
>>> for venture_question in venture.questions.all():
... venture_question.question.title, [answer.text for answer in venture_question.answers.all()]
...
(u'What is this?', [u"It's another venture with the same question and it's own answers..."])