Home > Software engineering >  How to implement recursive in Django Serializers
How to implement recursive in Django Serializers

Time:12-17

My serializers class

class ConditionSerializers(serializers.ModelSerializer):
 
 class Meta:
     model = TblCondition
     fields = ['id','operator','condition','relation']

class ConditionSerializers(serializers.ModelSerializer):
 relation_with=ConditionSerializers(many=False)
 class Meta:
     model = TblCondition
     fields = ['id','operator','relation_with','condition','relation']


class RuleSerializers(serializers.ModelSerializer):

 conditiontbl=ConditionSerializers(many=True)

 class Meta:
     model = TblRule
     fields = ['rule_table_no','rule_no','rule_name','columns','data_file','true','conditiontbl' ]

My model class

class TblRule(models.Model):
    rule_table_no=models.AutoField(primary_key=True)
    rule_no=models.IntegerField(blank=False)
    rule_name=models.CharField(max_length=100,blank=False)
    columns=models.CharField(max_length=100)
    data_file=models.CharField(max_length=100)
    true=models.CharField(max_length=100)


class TblCondition(models.Model):
    rule=models.ForeignKey(TblRule, on_delete=models.CASCADE,related_name='conditiontbl')
    operator=models.CharField(max_length=100)
    condition=models.CharField(max_length=100)
    relation=models.CharField(max_length=50,blank=True)
    relation_with=models.OneToOneField(to='self',null=True,blank=True,on_delete=models.CASCADE)

Getting these results in postman API by calling ruletbl models

[
    {
        "rule_table_no": 2,
        "rule_no": 1,
        "rule_name": "Age Discritization",
        "columns": "Age",
        "data_file": "Data1",
        "true": "Teen",
        "conditiontbl": [
            {
                "id": 4,
                "operator": ">",
                "relation_with": null,
                "condition": "15",
                "relation": ""
            },
            {
                "id": 5,
                "operator": "<=",
                "relation_with": {
                    "id": 4,
                    "operator": ">",
                    "condition": "15",
                    "relation": ""
                },
                "condition": "25",
                "relation": "and"
            }
        ]
    },
    {
        "rule_table_no": 3,
        "rule_no": 1,
        "rule_name": "Age Discritization",
        "columns": "Age",
        "data_file": "Data1",
        "true": "Young",
        "conditiontbl": []
    }
]

Results I want :

[
  {
    "rule_table_no": 2,
    "rule_no": 1,
    "rule_name": "Age Discritization",
    "columns": "Age",
    "data_file": "Data1",
    "true": "Teen",
    "conditiontbl": [
      {
        "id": 7,
        "operator": ">",
        "relation_with": null,
        "condition": "15",
        "relation": ""
      },
      {
        "id": 6,
        "operator": "<=",
        "relation_with": {
          "id": 7,
          "operator": ">",
          "relation_with":  
           {
            "id": 7,
            "operator": ">",
            "relation_with": null,
            "condition": "15",
            "relation": ""
          },



          "condition": "15",
          "relation": "or"
        },
        "condition": "25",
        "relation": "and"
      }
    ]
  },
  {
    "rule_table_no": 3,
    "rule_no": 1,
    "rule_name": "Age Discritization",
    "columns": "Age",
    "data_file": "Data1",
    "true": "Young",
    "conditiontbl": []
  }
]

You can see conditiontbl list fileds in ruletbl model (e.g. in JASON results), inside conditiontbl filed we have objects of tblcondition models with fileds ("relation_with"), and this relation_with filed is again refering to its own tblcondition model you can see its second object. I want this refering in relation_with fileds to its own conditiontbl model to be recursive. Any solution ?

CodePudding user response:

In Django, recursive serialization can be implemented by creating a custom serializer class that extends the BaseSerializer class and overrides the to_representation() method

CodePudding user response:

from django.core.serializers import serialize

from django.core.serializers.json import DjangoJSONEncoder from django.db import models from rest_framework import serializers

class Node(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) value = models.CharField(max_length=255)

class NodeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Node fields = ('url', 'parent', 'value')

root = Node.objects.get(pk=1)

serialized_data = serialize('json', [root], cls=DjangoJSONEncoder)

  • Related