Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get serializer data by foreign key

I need to pass data from EmployeeSerializer to VacationSerializer as nested json. This is my serializer.py:

class EmployeeSerializer(serializers.ModelSerializer):
    

    class Meta:
        model = Employee
        fields = ('pk', 'first_name', 'surname', 'patronymic', 'birthday', 'email', 'position', 'phone_number')

class VacationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Vacation
        fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee')

and my models.py:

class Employee(models.Model):
    first_name = models.CharField("Name", max_length=50)
    surname = models.CharField("surname", max_length=50)
    patronymic = models.CharField("patronymic", max_length=50)
    birthday = models.DateField()
    email = models.EmailField()
    position = models.CharField("position", max_length=128)
    phone_number = models.CharField("phone", max_length=12, null=True)
    is_deleted = models.BooleanField(default=False)

    def __str__(self):
        return f'{self.surname} {self.first_name} {self.patronymic}'

class Vacation(models.Model):
    start_date = models.DateField()
    end_date = models.DateField()
    employee_id = models.ForeignKey(Employee, related_name='employee', on_delete=models.PROTECT, default=-1)

    def __str__(self):
        return f'{self.start_date} - {self.end_date}'

    @property
    def date_diff(self):
        return (self.end_date - self.start_date).days

in views.py I have this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@api_view(['GET', 'POST'])
def vacations_list(request):
    
    if request.method == 'GET':
        data = Vacation.objects.all()
        serializer = VacationSerializer(data, context={'request': request}, many=True)

        return Response(serializer.data)

I’ve tried this:

class VacationSerializer(serializers.ModelSerializer):
    employee = EmployeeSerializer(read_only=True, many=True)
    class Meta:
        model = Vacation
        fields = ('pk', 'start_date', 'end_date', 'employee_id', 'employee')

but it doesn’t show me even empty nested json, it shows me only VacationSerializer data.

I easily can access VacationSerializer from EmployeeSerializer using PrimaryKeySerializer or any other serializer and get nested json where VacationSerializer data is nested in EmployeeSerializer data. But I want it opposite – nested json of employee related to this vacation. How to achieve this?

>Solution :

That is because of the naming on your model. You need to serialize the ’employee_id’ field:

class VacationSerializer(serializers.ModelSerializer):
    employee_id = EmployeeSerializer()

    class Meta:
        model = Vacation
        fields = ('pk', 'start_date', 'end_date', 'employee_id')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading