Robert Lu
Robert Lu

Reputation: 2159

How can I serialize single object's fields in django(without pk and model)

In Django, I have this model(it inherited from AbstractBaseUser):

class User(AbstractBaseUser):
    username = models.CharField(max_length=20, unique=True)
    realname = models.CharField(max_length=10)
    grade = models.CharField(max_length=10)
    studentNo = models.CharField(max_length=10)
    email = models.EmailField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

I want serialize a single User object to:

{
    "studentNo": "lu", 
    "realname": "lu", 
    "email": "[email protected]", 
    "grade": "lu", 
    "username": "admin", 
    "is_active": true
}

Is there any utility to serialize?


I found the document form django. Follow the cocument, It can only serialize a list and must with model and pk. It like that:

[
    {
        "fields": {
            "email": "[email protected]", 
            "is_active": true, 
            "studentNo": "lu", 
            "username": "admin", 
            "realname": "lu", 
            "grade": "lu"
        }, 
        "pk": 1, 
        "model": "account.user"
    }
]

I also try the build-in module json, but I must get every field's key and value, save to list, and serialize it. It looks not elegant.

Upvotes: 0

Views: 1940

Answers (3)

minbaba
minbaba

Reputation: 1

from django.core.serializers.json import Serializer
class CustomSerializer(Serializer):
    def get_dump_object(self, obj):
        return self._current

I use this in new Django version

Upvotes: 0

WeizhongTu
WeizhongTu

Reputation: 6414

I have another method to do this

import json
from models import User

UserList = [ {"studentNo": user.studentNo, "realname": user.realname, "email": user.email, "grade": user.grade,
    "username": user.username, "is_active": user.is_active } for user in User.objects.all()]

f = open('jsonfile.txt','w')
json.dump(UserList,f,indent=4) # elegant output
f.close()

Upvotes: 0

Adem Öztaş
Adem Öztaş

Reputation: 21446

You can create custom Serializer like this,

from django.core.serializers.json import Serializer, DjangoJSONEncoder
from django.utils import simplejson

class NewSerializer(Serializer):
    def end_serialization(self):
        cleaned_objects = []

        for obj in self.objects:
            del obj['pk']
            del obj['model'] 
            cleaned_objects.append(obj)

        simplejson.dump(cleaned_objects, self.stream, cls=DjangoJSONEncoder, **self.options)

Upvotes: 2

Related Questions