Django Deep Serialization - Enforcing Foreign Foreign Key Constraints

I have two models with a foreign key relationship:

class Company(models.Model): field 1 field 2 class Employee(models.Model): company = Model.ForeignKey('Company') field 3 field 4 

I would like JSON to serialize an instance of the company and include all employees with foreign key relationships in it. IE, I would like to create JSON that looks something like this: it includes all fields for the company and all fields for all related employees.

 [ { "pk": 2, "model": "app.company", "fields": { "field1": "value", "field2": "value", "employee": [ { "pk": 19, "model": "app.employee", "fields": { "field3": "value", "field4": "value", } }, { "pk": 25, "model": "app.employee", "fields": { "field3": "value", "field4": "value", } } ] } } ] 

Django serializer does not serialize relationships. Other questions here ask how to deeply serialize, but in the opposite direction - IE, serialize the employee with your related company. Answers to these questions indicated that the django-full-serializer wadofstuff plugin allows you to do such deep serialization. The problem is that the wadofstuff plugin only follows these relationships one-sidedly - it will not follow the reverse external key constraint. So, I'm trying to drop my own here. Any suggestions on how to do this?

+4
source share
1 answer

So here is a super-budget way to do this that works for my purposes, but I feel that there should be a better way (including it here if others are looking for how to do this). This only works for me because I send only one company object at a time, and therefore the fact that it obviously does not preserve the hierarchy of relations does not really matter.

This instance of the company "company":

 companyJSON = serializers.serialize('json', [company, ]) employeeJSON = serializers.serialize('json', company.employee_set.all()) fullJSON = companyJSON[:-1] + ", " + employeeJSON[1:] 
0
source

Source: https://habr.com/ru/post/1442120/


All Articles