Save multiple values in foreign key django
I wanted to save multiple relational objects in a foreign key but unfortunately, I'm getting an error which I attached below. I already have the object with ID of 189 in my DB
error:
{
"tags": [
"Invalid pk \"189\" - object does not exist."
]
}
views.py
queryset = PackageRoom.objects.all()
serializer = PackageRoomSerializer(queryset, many=True)
return Response(serializer.data)
serializers.py
class PackageRoomSerializer(serializers.ModelSerializer):
tags = serializers.PrimaryKeyRelatedField(queryset=PackageRoom.objects.all(), many=True)
class Meta:
model = PackageRoom
fields = ['id', 'name', 'description', 'tags']
models.py
class Tag(models.Model):
name = models.CharField(max_length=255, default='')
description = models.CharField(max_length=255, default='')
singleline = models.ManyToManyField(Singleline)
class Meta:
db_table = 'tags'
class PackageRoom(models.Model):
name = models.CharField(max_length=255, default='')
tags = models.ForeignKey(Tag, on_delete=models.PROTECT)
class Meta:
db_table = 'package_rooms'
It was a silly mistake that I was doing there that I was passing the PackageRoom model in my serializer but I need to pass the Tag model instead.
class PackageRoomSerializer(serializers.ModelSerializer):
tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True)
class Meta:
model = PackageRoom
fields = ['id', 'name', 'description', 'tags']