外键字段始终在views.py中显示为None,但在数据库中不显示为空

时间:2017-04-13 01:18:17

标签: python django

我有一个django应用程序,我想设置一个工作表对象,其中包含一个节对象列表,其中每个节对象都有一个答案列表。

在下面显示的 views.py 的摘录中,我试图将与工作表关联的第一部分传递给渲染功能。

每当我在 views.py 文件中的以下函数中获得单个section对象时,section对象就没有任何与之关联的答案。但是,我知道我已经的部分有与之相关的答案,因为当我执行GET请求(或者使用由django rest框架自动设置的可浏览API)时,我可以请注意,与 views.py 中显示的函数中的ID相同的部分将长答案列表作为其属性之一。

尽管如此,当我打印出如下所示的section.answers时,会显示myapp.Answer.None。

views.py

def worksheet_detail(request, pk):
    worksheet = Worksheet.objects.get(pk=pk)
    sections = Section.objects.filter(worksheet=worksheet)
    sections = list(sections)
    section = sections[1]
    print(section.answers)
    print(section.id)
    return render(request, 'worksheets/worksheet_detail.html', {
        'worksheet': worksheet,
        'section': section,
    })

models.py

class Worksheet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100, unique=True, default='')


class Section(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=100, unique=True, default='')
    worksheet = models.ForeignKey(
        Worksheet, related_name='sections', null=True)

    class Meta:
        ordering = ('created',)


class Answer(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    student_name = models.CharField(max_length=100, blank=True, 
                                    default='')
    num = models.IntegerField(default=0)
    section = models.ForeignKey(Section, related_name='answers', 
                                null=True)

serializers.py

class AnswerSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Answer
        fields = ('student_name', 'section', 'num', 'id',)

class SectionSerializer(serializers.HyperlinkedModelSerializer):
    answers = AnswerSerializer(many=True)

    def create(self, validated_data):
        answers_data = validated_data.pop('answers')
        section = Section.objects.create(**validated_data)
        for answer_data in answers_data:
            Answer.objects.create(section=section, **answer_data)
        return section

    class Meta:
        model = Section
        fields = ('name', 'worksheet', 'answers', 'id',)

class WorksheetSerializer(serializers.HyperlinkedModelSerializer):
    sections = SectionSerializer(many=True)

    def create(self, validated_data):
        sections_data = validated_data.pop('sections')
        worksheet = Worksheet.objects.create(**validated_data)
        for section_data in sections_data:
            Section.objects.create(worksheet=worksheet, **section_data)
        return section

    class Meta:
        model = Worksheet
        fields = ('name','id', 'sections')

0 个答案:

没有答案