Django serializer for one object

后端 未结 3 1279
一个人的身影
一个人的身影 2020-12-29 05:09

I\'m trying to figure out a way to serialize some Django model object to JSON format, something like:

j = Job.objects.get(pk=1)
#############################         


        
相关标签:
3条回答
  • 2020-12-29 05:30

    Method-1

    Use Django Serializer with python format

    from django.core import serializers
    
    j = Job.objects.get(pk=1)
    response = serializers.serialize('python', [j], ensure_ascii=False)

    Method-2

    use json format while serializing and loads the string response

    import json
    from django.core import serializers
    
    j = Job.objects.get(pk=1)
    json_str_response = serializers.serialize('json', [j], ensure_ascii=False)
    response = json.loads(json_str_response)[0]

    Method-3

    Use Django REST Framework's Serializer class define a serializer class and serialize the instance as

    from rest_framework import serializers
    
    
    class JobSerializer(serializers.ModelSerializer):
        class Meta:
            model = Job
            fields = '__all__'
    
    
    j = Job.objects.get(pk=1)
    response = JobSerializer(instance=j).data
    

    Reference
    1. Serializer Django model object

    0 讨论(0)
  • 2020-12-29 05:31

    I would suggest using Django's model_to_dict. If I'm not mistaken, serializers.serialize() relies on it, too, but it only works for list, not single model instance. That's how you get a dict instance with your model fields out of a single model:

    from django.forms.models import model_to_dict
    
    # assuming obj is your model instance
    dict_obj = model_to_dict( obj )
    

    You now just need one straight json.dumps call:

    import json
    json.dumps(dict_obj)
    
    0 讨论(0)
  • 2020-12-29 05:41

    How about just massaging what you get back from serializers.serialize? It is not that hard to trim off the square brackets from the front and back of the result.

    job = Job.objects.get(pk=1)
    array_result = serializers.serialize('json', [job], ensure_ascii=False)
    just_object_result = array_result[1:-1]
    

    Not a fancy answer but it will give you just the object in json notation.

    0 讨论(0)
提交回复
热议问题