Skip to content Skip to sidebar Skip to footer

Serializing Foreign Key Field

I have the following models: class Question(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) text = models.CharField(max_length=255,default='',blank=

Solution 1:

I hope, I understand your question correctly.

Your models.py

class Question(models.Model):
        test = models.ForeignKey(Test, on_delete=models.CASCADE)
        text = models.CharField(max_length=255,default='',blank=False)
        number = models.IntegerField()

        def __str__(self):
            return self.text



class Test(models.Model):
        PRIVACY_TYPES = (
            ('PR', 'Private'),
            ('PU', 'Public'),
        )
        user = models.ForeignKey(User, on_delete=models.PROTECT)
        name = models.CharField(max_length=255,default='',blank=False)
        datecreated = models.DateTimeField(auto_now=True)
        privacy = models.CharField(choices=PRIVACY_TYPES, default='PR',max_length=15)
        testtime = models.IntegerField(default=30)

My question is updated to show you what ForeignKey means. ForeignKey means ManyToOne. You have ForeignKey field in Question Model with reference to Test Model. Idea is, that you have Many Question and One Test (ManyToOne), and vice-versa One Test and Many Question.

This is solution below.

classTestSerializer(serializers.ModelSerializer):
    question_set = QuestionSerializer(many=True)
    user = serializers.ReadOnlyField(source='user.username')

    classMeta:
        model = Testfields= ('id', 'name', 'privacy', 'testtime', 'user', 'question_set')
        related_object = 'question'

And now use it,,,

test_obj = Test.objects.get(pk=1)
test_serializer = TestSerializer(instance=test_obj)
print(test_serializer.data)

Post a Comment for "Serializing Foreign Key Field"