models.py

class IP(models.Model):
     name = models.CharField(max_length=30, unique=True)
     address = models.CharField(max_length=50, unique=True)

class IPGroup(models.Model):
    name = models.CharField(max_length=50, unique=True)
    ips = models.ManyToManyField('IP', through='IPGroupToIP')

class IPGroupToIP(models.Model):
    ip_group = models.ForeignKey('IPGroup', on_delete=models.CASCADE)
    ip = models.ForeignKey('IP', on_delete=models.CASCADE)


serializers.py

class IPGroupCreateSerializer(serializers.ModelSerializer):
    ips = serializers.ListField()
    class Meta:
        model = IPGroup
        fields = ['name', 'ips']

@transaction.atomic()
def create(self, validated_data):
    ips_data = validated_data.pop('ips', None)
    ip_group = IPGroup.objects.create(name=validated_data['name'])
    if ips_data:
        for ip in ips_data:
            ip_obj, created = IP.objects.get_or_create(name=ip['name'], 
address=ip['address'])
            IPGroupToIP.objects.create(ip_group_id=ip_group.id, ip_id=ip_obj.id)
    return ip_group


views.py

class IPGroupCreateView(generics.CreateAPIView):
    queryset = IPGroup.objects.get_queryset()
    serializer_class = IPGroupCreateSerializer


JSON payload

{ "ips": [{"name":"example.com", "address":"10.1.1.9"}], "name": "ipgroup1" }


Expected behavior

{"name": "ipgroup1", "ips": [{"name": "example.com",  "address": "10.1.1.9"}]}


Actual behavior


*TypeError at /api/v1/ip-group/'ManyRelatedManager' object is not iterable*



This strangely works if i set write_only=True to the ListField but then the 
**ips** fiels is not available in the serializer response data. I went 
through the documentation and did not see this behavior mentioned anywhere. 
What am I doing wrong ?

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to