How to Serialize a Relation Onetoone in Django with Rest Framework?

I have a class PersonProfile, and a class Person. In the class Person i have a relationship OneToOne with PersonProfile. How can i Serialize that?

class PersonProfile(models.Model):
    interests = models.CharField(max_length=200, blank=True)
    researchLines = models.CharField(max_length=200, blank=True)
    loginName = models.CharField(max_length=50, blank=True)

class Person(models.Model):
    profile = models.OneToOneField(PersonProfile)
    enviroment = models.ForeignKey(Enviroment, related_name="persons")

2 Answers

You can create custom serializer fields to create your custom PersonSerializer. You can add fields to get values from Enviroment.

class PersonSerializer(serializers.HyperlinkedModelSerializer):
    interests = serializers.CharField(source='profile.interests')
    researchLines = serializers.CharField(source='profile.researchLines')
    loginName = serializers.CharField(source='profile.loginName')
    # --- FIELDS FOR enviroment 
    class Meta:
        model = Person
        fields = ('interests', 'researchLines', 'loginName',
                 #-- enviroment fields
                 )

You can also use serializers.ModelSerializer

class PersonSerializer(serializers.ModelSerializer):
   #-------------------------
4

I recently stumbled upon something similar and here is what I did for serializing the Person which is in OneToOne relation with PersonProfile.

class PersonProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = PersonProfile
        fields = __all__  # in your case since you are using all fields.

class PersonSerializer(serializers.ModelSerializer):
    person = PersonProfileSerializer(required=True)
    class Meta:
        model = Person
        fields = __all__

    # Now override the default create method to create a new object.
    # A similar overriding can be done for update as well.
    def create(self, validated_data):
        """
        Make necessary modifications as per your requirements
        """
        person_profile = PersonProfileSerializer.create(PersonProfileSerializer(), validated_data)
        person, created = Person.objects.create(profile=person_profile)
        return person

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest