Home > Net >  Django Test: Incorrect type. Expected pk value, received str
Django Test: Incorrect type. Expected pk value, received str

Time:03-15

I have a simple model having a foreign key:

class Job(models.Model):
    resource = models.ForeignKey(Resource, on_delete=models.RESTRICT, related_name="resource_jobs")
    required_resource = models.FloatField(default=0)

Here is the viewset:

class JobViewSet(ModelViewSet):
    queryset = Job.objects.all()
    serializer_class = JobSerializer

I am writing a test to create this Job object like this.

self.detail_url: str = "factory:jobs-detail"

self.resource = Resource.objects.create(**self.resource_data)

self.job_data = {
    "resource": self.resource,
    "required_resource": 20,
}

def test_create(self) -> None:
    response: Response = self.client.post(
        self.list_url, data=self.job_data
    )
    print(response.data)
    self.assertEqual(response.status_code, 201)

Upon running the test I get an error: {'resource': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]} How do I pass this object in this dictionary.

Thank you for any help.

CodePudding user response:

You never pass model objects through a serializer: a serializer serializer to a stream of characters like JSON, XML, etc.

You should pass the primary key of the item, so:

self.job_data = {
    'resource': self.resource,pk,
    'required_resource': 20,
}
  • Related