I am trying to create a simple Many to Many relationship. I have two models: IP and IPCollection, an IP can belong to 0 or more collections, and an IPCollection consists of IP addresses.
After following the documentation, I thought I had got it to work. But I could not select existing IP addresses when creating a new collection in the API interface.
Following this post: Lists are not currently supported in HTML input I managed to solve the problem, allowing me to create a new IPCollection while choosing between the existing IP's from a form. Everything seemed to be fine.
However, once I implemented the solution provided in that stackoverflow post, a new problem occured: I can't retrieve my IPs anymore.
I have my two endpoints: /ipcollections and /ips, and whenever I try to do a GET request to /ips I get the following error:
TypeError at /ips/
__init__() takes 1 positional argument but 2 were given
I have tried searching for a solution to this problem, but so far nothing seems to work.
This is wat my serializers look like after implementing the solution from the other stackoverflow post:
class IpSerializer(serializers.PrimaryKeyRelatedField, serializers.ModelSerializer):
class Meta:
model = Ip
fields = ('address',)
class IpCollectionSerializer(serializers.ModelSerializer):
ipAddresses = IpSerializer(many=True, queryset=Ip.objects.all())
class Meta:
model = IpCollection
fields = ('title', 'ipAddresses')
And my models:
class Ip(models.Model):
address = models.CharField(max_length=100)
def __str__(self):
return self.address
class IpCollection(models.Model):
title = models.CharField(max_length=100)
ipAddresses = models.ManyToManyField(Ip, related_name='ipAddresses')
The problem seems to be caused by the 2nd parameter in the IpSerializer, since it works again after removing the PrimaryKeyRelatedField argument. But I can't seem to get the HTML form in the API interface to work in any other way than adding this parameter to the IpSerializer.
Any thoughts/tips on what I might be doing wrong are very welcome!