简体   繁体   中英

Django REST Serializer Many to Many field displays only through table id, need list of many records

How do i get list of Many 2 Many field objects? I am just getting the ID.

This one is MainHost class which is having Many2Many field

class MainHost(models.Model):
    host_id =  models.IntegerField(verbose_name='HOST ID', primary_key=True)
    group = models.ManyToManyField(MainGroup, related_name='hostgroups', through ='HostGroup')

This class is created for through keyword, contains all the relationship for Host and Group

class HostGroup(models.Model):
    host = models.ForeignKey(MainHost, on_delete=models.CASCADE)
    group = models.ForeignKey(MainGroup, on_delete=models.CASCADE)

This class contains all the Groups data

class MainGroup(models.Model):
    group_id =  models.IntegerField(verbose_name='GROUP ID', primary_key=True)

Serializer class

class MainGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = MainGroup
        fields = (
            'group_id', 
            'group_name',
             ....
            'groupinv_path'
        ) 

HostSerialzer class

class MainHostSerializer(serializers.ModelSerializer):
    group = serializers.PrimaryKeyRelatedField(queryset=HostGroup.objects.all(), many=True)
    class Meta:
        model = MainHost
        fields = (
            'host_id', 
            'host_name',
            'group'
        )

class HostGroupSerializer(serializers.ModelSerializer):
    host = MainHostSerializer()
    group = MainGroupSerializer()
    class Meta:
        model = HostGroup
        fields = (
            'id',
            'host', 
            'group'  
        )  
        read_only_fields = ['host', 'group']
        def create(self, validated_data):
            host_data = MainHost.objects.create(**validated_data.get('host'))
            group_data = MainGroup.objects.create(**validated_data.get('group'))

            conn = HostGroup.objects.create(
                host=host_data, 
                group=group_data
            )
            return conn  

MainHost API response

    {
        "host_id": 4087,
        "host_name": "10.240.144.2",
        "group": [
            280,
            285,
            300
        ]
    }

280, 285 and 300 are group objects from MainGroup I want to see the whole object content.

MainGroup Response is showing the complete object.

    {
        "group_id": 2,
        "group_name": "test_environment_production",
        "total_hosts": 1,
        "total_groups": 0,
        "description": "imported",
        "group_variables": "{}",
        "groupinv_path": ""
    }

Even Response for GroupHost API is having complete Group Object.

    {
        "id": 1,
        "host": {
            "host_id": 4087,
            "host_name": "10.100.144.2",
            "group": [
                280
            ]
        },
        "group": {
            "group_id": 280,
            "group_name": "aruba",
            "total_hosts": 539,
             .....
            "groupinv_path": "TEC/GT/Swi/test.ini"
        }
    }

Can specify the nested representation by using the depth option as shown in the DRF docs here:

https://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

Removing this line: group = serializers.PrimaryKeyRelatedField(queryset=HostGroup.objects.all(), many=True)

from MainHostSerializer(serializers.ModelSerializer):

and adding depth = 2 it worked fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM