Client.post is not passing the FK

Hope someone can help me out here, I am trying to test a post method on an API, but the post method is not working as expected.

When I pass the payload to the post method, the points and de code fields are loaded but the shopper and card fields, which are both Foreing Keys, are not loaded and a null value is passed, as they are required fields I ended up getting an error.

I did check, and the values for self.shopper.pk and self.card.pk are correct.

MYCARDS_URL = reverse('mycards:mycards-list')

def test_create_mycards(self):
    """Test creating a mycards"""
    payload = {
        'shopper': self.shopper.pk,
        'card': self.card.pk,
        'points': 0,
        'code': "code",
    }

    res = APIClient().post(MYCARDS_URL, payload)

I did check to see if was something related to my serializer, but it is all good as you can see:

class MycardsSerializer(serializers.ModelSerializer): """Serializer for cards."""

class Meta:
    model = MyCards
    fields = ['id', 'shopper', 'card', 'updated', 'created']
    read_only_fields = ['id', 'created']

class MycardsDetailSerializer(MycardsSerializer): """Serializer for card detail view."""

class Meta(MycardsSerializer.Meta):
    fields = MycardsSerializer.Meta.fields + [
        'points', 'code']

Here is also my viewset which seems to be ok:

class MycardsViewSet(viewsets.ModelViewSet):
    """View for manage card APIs."""

    serializer_class = serializers.MycardsDetailSerializer
    queryset = MyCards.objects.all()
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """Retrieve cards for authenticated user."""
        shoppers = list(Shopper.objects.all().filter(
            user=self.request.user).values_list('id'))

        return self.queryset.filter(shopper=shoppers[0]).order_by('-id')

    def get_serializer_class(self):
        """Return the serrializer class for request."""
        if self.action == 'list':
            return serializers.MycardsSerializer

        return self.serializer_class

    def perform_create(self, serializer):
        """Create a new recipe."""
        serializer.save()
Back to Top