Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

How to serialize a relation OneToOne in Django with Rest Framework?

Writer Matthew Harrington

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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