Home > Mobile >  Save multiple relational objects in foreign key django
Save multiple relational objects in foreign key django

Time:12-15

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 
}

CodePudding user response:

You can use PrimaryKeyRelatedField in your serializer and set its many=True:

class PackageSerializer(serializers.ModelSerializer):

    tags = serializers.PrimaryKeyRelatedField(queryset=PackageRoom.objects.all(), many=True)

    class Meta:
        model = PackageRoom
        fields = ("name", "tags")

Docs is: https://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield

  • Related