Issue
I want to make one to many relation between models and in Django, we need to use ForeignKey for it. I will multiple IDs of the relational objects in an array from the frontend but I'm confused that how will I save these multiple relational object in it? each package room can have multiple tags but the tags will have only one package room.
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'
the JSON object I will receive from the frontend
{
"name": "Test Room",
"tags": [1, 2, 3, 4, 5] // IDs of Tags
}
Solution
You can use PrimaryKeyRelatedField
in your serializer and set its many=True
:
class PackageSerializer(serializers.ModelSerializer):
tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True)
class Meta:
model = PackageRoom
fields = ("name", "tags")
Docs is: https://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield
Answered By - Amin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.