如何在 Django 序列化程序中实现递归

How to implement recursive in Django Serializers

提问人:Pratish Dewangan 提问时间:12/13/2022 最后编辑:Pratish Dewangan 更新时间:12/20/2022 访问量:116

问:

我的序列化程序类

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' ]

我的模型类

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)

通过调用 ruletbl 模型在 postman API 中获取这些结果

[
    {
        "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": []
    }
]

我想要的结果:

[
  {
    "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": []
  }
]

您可以在 ruletbl 模型中看到 conditiontbl list fileds(例如在 JASON 结果中),在 conditiontbl 字段中,我们有带有 fileds (“relation_with”) 的 tblcondition 模型的对象,并且这个relation_with file 再次引用它自己的 tblcondition 模型,您可以看到它的第二个对象。我希望relation_with文件中对它自己的 conditiontbl 模型的引用是递归的。有什么解决方案吗?

python django 递归 django-serializer

评论

0赞 Futs TV 12/13/2022
你看过这个吗...这里
0赞 Pratish Dewangan 12/14/2022
是的,我看到并尝试申请我目前的问题,但仍然没有得到正确的结果

答:

0赞 Rangga Restu Kusuma 12/13/2022 #1

在 Django 中,递归序列化可以通过创建一个自定义序列化程序类来实现,该类扩展了 BaseSerializer 类并覆盖了 to_representation() 方法

评论

0赞 Pratish Dewangan 12/14/2022
你能展示一下代码吗
0赞 Rangga Restu Kusuma 12/17/2022 #2
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)