[Django]-Object of type Company is not JSON serializable when writing tests

1👍

The problem is that you are passing a python object via a json in your test, this section

self.valid_coupon_data = {
"company": Company.objects.get(id=1),   # This is the error point! you are passing python object not a json.
"name": "Coupon Updated",
"added": "2018-11-30",
"code": "TESTCODE"
}

And passing just integer value like other answers will not work either. you should pass json of company object too. like this:

company = Company.objects.get(id=1)

self.valid_coupon_data = {
"company": {
     "id": company.id,
     "name": company.name,
     "added": company.added
},
"name": "Coupon Updated",
"added": "2018-11-30",
"code": "TESTCODE"
}

Note
By the way if you are using django rest, then the way you are returning data in your views is not correct. use to_representation or serializer.data methods. it’s not that well to use json.dump when you have a powerfull library like django-rest-framework. You can also return json as is with Response library of django-rest. like return Response(jsonData)

If you want more clear answer, please provide make_coupon_request method codes. to see what’s going on in there.

2👍

The problem may lies in this statement,

self.valid_coupon_data = {
    "company": Company.objects.get(id=1), # here
    "name": "Coupon Updated",
    "added": "2018-11-30",
    "code": "TESTCODE"
}


It's clear that you are trying to send a json data and unfortunately it contains a non-serializable data of Company type.


According to the CouponSerializer you'd provided, the below json is enough to create/update the Coupon instance.

{
    "company": 1, # provide only integer value
    "name": "Coupon Updated",
    "added": "2018-11-30",
    "code": "TESTCODE"
}
👤JPG

Leave a comment