0

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 
}

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

queryset=Tag.objects.all() right? @Amin
Yeah sorry about that! I fixed it. @dhiraka

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.