在外键django中保存多个值
Save multiple values in foreign key django
我想在一个外键中保存多个关系对象,但不幸的是,我收到了一个错误,附在下面。我的数据库中已经有 ID 为 189 的对象
错误:
{
"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'
我在那里犯了一个愚蠢的错误,我在我的序列化程序中传递了 PackageRoom 模型,但我需要传递 Tag 模型。
class PackageRoomSerializer(serializers.ModelSerializer):
tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True)
class Meta:
model = PackageRoom
fields = ['id', 'name', 'description', 'tags']
我想在一个外键中保存多个关系对象,但不幸的是,我收到了一个错误,附在下面。我的数据库中已经有 ID 为 189 的对象
错误:
{
"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'
我在那里犯了一个愚蠢的错误,我在我的序列化程序中传递了 PackageRoom 模型,但我需要传递 Tag 模型。
class PackageRoomSerializer(serializers.ModelSerializer):
tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True)
class Meta:
model = PackageRoom
fields = ['id', 'name', 'description', 'tags']