Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize objects with specific fields using serializers.serialize in django?

Tags:

python

django

I want to serialize django models for only some specific fields. How do I do that. I have a model as below:

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

    def __str__(self):
        return self.first_name

I am using serailizer as:

from django.core import serializers

serializers.serialize('json', Person.objects.all(), content_type='application/json')

My output is:

[
   {
       model: "myapp.Person",
       pk: 1,
       fields: {
           "first_name": "hello",
           "last_name": "world"
       }
   }
]

I want to serialize this model only for first_name and output must be as below:

[
   {
       model: "myapp.Person",
       pk: 1,
       fields: {
           "first_name": "hello"
       }
   }
]
like image 481
Dipesh Bajgain Avatar asked Jun 05 '26 00:06

Dipesh Bajgain


1 Answers

Person.objects.all() also has the first_name value in it. You can access it via:

for p in Person.objects.all():
    p.first_name

Please read the documentation for more details.

Update:

For serialization, try like this:

serializers.serialize("json", Person.objects.all(), fields=["first_name", "last_name"])
like image 60
ruddra Avatar answered Jun 07 '26 14:06

ruddra