Programmingjoe
Programmingjoe

Reputation: 2249

How to create foreign key related objects during object create call with the Django Rest Framework?

Let's say I have model A and B.

Model A has a range of fields including a user field which is filled in with the user who creates an object A.

When object A is created I want to create a bunch of object B's using the user that created object A and possible using object A itself as a foreign key.

My Model A ViewSet looks like this:

class OrganizationViewSet(DynamicModelViewSet):
    queryset = Organization.objects.all()
    serializer_class = OrganizationSerializer
    permission_classes = (IsAdminOfPermission,)

So when an organization is created I want to create a bunch of object B's using the user that created the organization and possibly using the organization object itself.

How do I do this?

Upvotes: 1

Views: 243

Answers (2)

Aneesh R S
Aneesh R S

Reputation: 3827

Implement the logic in the Serializer create method

class OrganizationSerializer(serializers.ModelSerializer):
    # ...
    # ...
    # ...
    def create(self, validated_data):
        user = validated_data.get('user')
        organization = Organization.objects.create(**validated_data)
        # create model B with `user` and `organization`
        # like ModelB.objects.create(user=user, organization=organization, ...)
        return organization

To pass the user from view to the serializer, you have to send it through the save method of the serializer.

for example

class OrganizationList(APIView):
    queryset = Organization.objects.all()
    serializer_class = OrganizationSerializer
    permission_classes = (IsAdminOfPermission,)

    def post(self, request, format=None):
       serializer = OrganizationSerializer(data=request.data)
       serializer.is_valid(raise_exception=True)
       serializer.save(user=request.user)
       return Response(serializer.data, status=status.HTTP_201_CREATED)

Upvotes: 2

sahutchi
sahutchi

Reputation: 2233

This might not be the most elegant approach... but here's how I'd do it:

class DemoHandler(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, format=None):
       m = ModelA(..., user=request.user, ...)
       m.save()
       m2 = ModelB( ... )
       ...

In other words, I'd just manually define with APIView vice a ModelViewset. Hopefully somebody has a better approach.

Upvotes: 0

Related Questions