Skip to content

Unable to Serialize one resource from a virtual field

To easily cover one of my CoopStarter use case, I did implement a virtual field as follows:

    def review(self):
        try:
            return self.reviews.all()[0]
        except:
            return None

This virtual Field is linked to the reviews ManyToMany field defined here,as follows:

    reviews = models.ManyToManyField(Review, verbose_name="Associated review", blank=True, related_name='resources')

Requesting the Resource object directly now results in


TypeError at /resources/3/

Object of type 'Review' is not JSON serializable

Request Method: 	GET
Request URL: 	http://localhost:8000/resources/3/
Django Version: 	1.11.23
Exception Type: 	TypeError
Exception Value: 	

Object of type 'Review' is not JSON serializable

Exception Location: 	/usr/lib/python3.6/json/encoder.py in default, line 180
Python Executable: 	/usr/bin/python3
Python Version: 	3.6.8
Python Path: 	

['/home/balessan/workspace/coopstarter',
 '/usr/lib/python36.zip',
 '/usr/lib/python3.6',
 '/usr/lib/python3.6/lib-dynload',
 '/home/balessan/.local/lib/python3.6/site-packages',
 '/usr/local/lib/python3.6/dist-packages',
 '/usr/lib/python3/dist-packages']

Server time: 	Sun, 1 Sep 2019 17:05:23 +0000
Traceback Switch to copy-and-paste view

    /home/balessan/.local/lib/python3.6/site-packages/django/core/handlers/exception.py in inner

                    response = get_response(request)

         ...
    ▶ Local vars 

The serialization of a single item is failing, when it is expected to return something like :

{ 
  review: 
  {
    @id: 'http://localhost:8000/reviews/1/'
    @type: 'coopstarter:review'
  }
}

If I bypass the thing, by returning an array of only one item, it works:

    def review(self):
        try:
            return self.reviews.all()[:1]
        except:
            return None

Returns

"review": {
    "@id": "http://localhost:8000/resources/3/review/",
    "@type": "ldp:Container",
    "ldp:contains": [
      {
        "@id": "http://localhost:8000/reviews/28/",
        "@type": "coopstarter:review",
        "permissions": [
          {
            "mode": {
              "@type": "view"
            }
          },
          {
            "mode": {
              "@type": "change"
            }
          },
          {
            "mode": {
              "@type": "control"
            }
          },
          {
            "mode": {
              "@type": "delete"
            }
          }
        ]
      }
    ],
    "permissions": [
      {
        "mode": {
          "@type": "view"
        }
      },
      {
        "mode": {
          "@type": "add"
        }
      }
    ]
  }

But it does not allow me to answer my use case as I am looking for an easy way to display this review status on the front side.

Looks like a bug to @sylvain