Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Objects with One-to-One Relationship Django

I am a newbie in django. I am working on a rest api. I have an optional "is a" relationship i.e Student is a Employee. I am trying to serialize these 2 models such that I get combined json result. Please let me know if anyone can help me with this. Thanks

class Employee(models.Model):
    full_name=models.CharField(max_length=100,blank=True)
    email_id=models.EmailField(max_length=100,blank=True)
    mobile_no=models.CharField(max_length=11,blank=True)
    is_job_ready=models.BooleanField(False)
    type=models.CharField(max_length=20,blank=True)
    location_preference=models.CharField(max_length=20,blank=True)

class Student(models.Model):
    college=models.CharField(max_length=100)
    year=models.CharField(max_length=20)
    is_with_college=models.BooleanField()
    employee=models.OneToOneField(Employee,primary_key=True)
like image 343
user1827423 Avatar asked May 30 '15 16:05

user1827423


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

Is it necessary to use Serializers in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is To_representation in Django?

to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.


2 Answers

The Django REST framework has some nice tools for serializing nested objects.

You need what they call a Nested Relationship. Like this -

from rest_framework import serializers

# define your models here ...

class EmployeeSerializer(serializers.ModelSerializer):
  class Meta:
    model = Employee
    fields = ('full_name', 'email_id', 'mobile_no', 'is_job_ready', 'type', 'location_preference')

class StudentSerializer(serializers.ModelSerializer):
  employee = EmployeeSerializer(read_only = True)

  class Meta:
    model = Student
    fields = ('college', 'year', 'is_with_college', 'employee')

Then, you can load your serializer and use it something like this -

from myapp.models import StudentSerializer

student = Student.objects.first()
serializer = StudentSerializer(student)

serializer.data
# { 'college': 'Naropa University',
#    'is_with_college': True,
#    'year': '2015'}
#    'employee': {
#      'full_name' : 'Chogyam Trungpa',
#      'email_id' : '[email protected]',
#      'mobile_no' : '555-555-5555',
#      'is_job_ready' : True,
#      'type' :'Teacher',
#      'location_preference' : 'Boulder, CO'
#    }
#  }
like image 159
metahamza Avatar answered Oct 18 '22 23:10

metahamza


You can go with @metahamza way, or use depth keyword refer docs here

Specifying nested serialization The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option:

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ['id', 'account_name', 'users', 'created']
        depth = 1

The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.

like image 27
5warag Avatar answered Oct 18 '22 23:10

5warag