I created this simple project to illustrate my problem.
These are my models:
class Zoo(models.Model):
name = models.CharField(max_length=30)
class Animal(models.Model):
name = models.CharField(max_length=30)
zoo = models.ForeignKey(Zoo)
开发者_运维问答 def speak(zelf):
return 'woof woof'
This is my base handler:
class ZooHandler(BaseHandler):
fields = ('id', 'name', 'speak')
def read(self, request):
z = Zoo.objects.get(pk=1)
qs = z.animal_set.all()
return qs
This is the result if I don't convert the queryset to a list:
[
{
"id": 1,
"name": "Tiger",
"speak": "woof woof"
},
{
"id": 2,
"name": "Panda",
"speak": "woof woof"
},
{
"id": 3,
"name": "Bear",
"speak": "woof woof"
},
{
"id": 4,
"name": "Parrot",
"speak": "woof woof"
},
{
"id": 5,
"name": "Dolphin",
"speak": "woof woof"
}
]
This is what happens if I do convert it to a list return list(qs)
:
[
{
"zoo_id": 1,
"_state": "<django.db.models.base.ModelState object at 0x2413f90>",
"id": 1,
"name": "Tiger"
},
{
"zoo_id": 1,
"_state": "<django.db.models.base.ModelState object at 0x241d590>",
"id": 2,
"name": "Panda"
},
{
"zoo_id": 1,
"_state": "<django.db.models.base.ModelState object at 0x241d6d0>",
"id": 3,
"name": "Bear"
},
{
"zoo_id": 1,
"_state": "<django.db.models.base.ModelState object at 0x241d750>",
"id": 4,
"name": "Parrot"
},
{
"zoo_id": 1,
"_state": "<django.db.models.base.ModelState object at 0x241d7d0>",
"id": 5,
"name": "Dolphin"
}
]
I lose the speak method result but gain a relational id and a _state object. Can anybody explain why this happens and how I can prevent it? This is just a test project I didn't wanna bore anybody trying to explain my real project.
Because you are not actually serializing Zoo objects, but Animal objects. Piston sees that you have a queryset of Animals, and tries to find an Animal handler - not finding one, it just serializes all the built-in objects, but not the custom method.
Define an AnimalHandler
class and move the fields
tuple to there, and it should work.
精彩评论