Home > database >  I want to create multiple objects with single foreign key relation
I want to create multiple objects with single foreign key relation

Time:10-06

I need to add multiple skills for one candidate in one request. As now i am getting the error cannot assign multiple instances to skill models

class CandidateSkill(models.Model):
    candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE,related_name="skills",)
    skills = models.ForeignKey("jobs.Skill", on_delete=models.CASCADE)

class CandidateSkillList(generics.ListCreateAPIView):
    serializer_class = CandidateSkillSerializer
    queryset = CandidateSkill.objects.all()

----------
class CandidateSkillSerializer(serializers.ModelSerializer):
    class Meta:
        model = CandidateSkill
        fields = ["id", "candidate", "skills"]

CodePudding user response:

In models.py file change many-to-many relationship then you can easily add multiple instances

skills = models.ManyToManyField("jobs.Skill")

CodePudding user response:

The are different ways to create multiple model instances with Django Rest Framework, but this solution use viewsets and override the create method.

from rest_framework import status, viewsets
from rest_framework.response import Response

class ThingViewSet(viewsets.ModelViewSet):

    # This view code provides both list and item create functionality

    queryset = CandidateSkill.objects.all()
    serializer_class = CandidateSkillSerializer

    def create(self, request, *args, **kwargs):
        # If the data is a list then many = True else many = False
        serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list))
        # Raise an exception if data is not valid
        serializer.is_valid(raise_exception=True)
        
        self.perform_create(serializer)
        # Get the headers infos
        headers = self.get_success_headers(serializer.data)
        # Return the response
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

You can post a data like this :

[{'candidate': 2, 'skills': 5}, {'candidate': 1, 'skills': 1}]

But make sure that skills and candidate id exists !

  • Related