So I have this test that generates a list of goal categories, which are the primary key then it populates the model described below. When it goes to UserInterestViews if I pass the list of goal_category_list I get an error that they aren't valid PKs, but when I just pass in 1 string it's fine. How do I pass in a list of primary keys to a ManyToManyField in the serializer?
the error I'm getting is
{'categories': [{'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got str.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got str.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got str.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got str.', code='invalid')]}]}
test
import json
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from cheers.models import GoalCategory
from dummy_factory.Factories import UserFactory
class UserInterestsTest(TestCase):
@classmethod
# Generates Test DB data to persist throughout all tests
def setUpTestData(cls) -> None:
cls.goal_category_list = ['health', 'fitness', 'academic', 'spiritual']
for gc in cls.goal_category_list:
GoalCategory.objects.create(category=gc, emoji_url='some_url')
cls.user = UserFactory()
def test_create(self):
response = self.client.post(reverse('set_user_interests'),
data=json.dumps({'user': str(self.user.uuid),
'categories': self.goal_category_list}),
content_type='application/json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
view.py
class UserInterestsView(APIView):
"""
View for UserInterests object
* requires token authentication
"""
# Create user interests
@swagger_auto_schema(
request_body=UserInterestsSerializer,
operation_description="Create user interests object"
)
def post(self, request):
serializer = UserInterestsSerializer(data=request.data)
if serializer.is_valid():
try:
serializer.save()
except django.db.utils.InternalError as e:
return Response(dict(error=e), status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
model.py
class UserInterests(AbstractBaseModel):
user = models.OneToOneField(User, on_delete=models.CASCADE)
categories = models.ManyToManyField(GoalCategory)
serializer.py
class GoalCategorySerializer(serializers.ModelSerializer):
class Meta:
model = GoalCategory
fields = ['category', 'emoji_url']
class UserInterestsSerializer(serializers.ModelSerializer):
categories = GoalCategorySerializer(many=True)
class Meta:
model = UserInterests
fields = ('user', 'categories', 'uuid')