Reputation: 839
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"
}
}
]
Upvotes: 2
Views: 6716
Reputation: 51968
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.
For serialization, try like this:
serializers.serialize("json", Person.objects.all(), fields=["first_name", "last_name"])
Upvotes: 12