How can I convert my json response to nested json where attributes are under another 'attribute'?
Question:
I am new to Django APIs. I am designing a api where response will be like this after a post request:
{ "set_attributes":
{
"name": "some value",
"age": "another value"
},
}
At present my response showing like this:
{
"Name": "some value",
"age": "another value"
}
I am using class based views and for forms I am using Django models. I did not render any html forms.
serializers.py:
class ContactSerializer(serializers.ModelSerializer):
Name = serializers.CharField(max_length=100)
Birthdate = serializers.DateField(default=datetime.now())
class Meta:
model = Contact
fields = ('Name', 'Birthdate', 'age')
class ListingSerializer(serializers.ModelSerializer):
age = serializers.Field(source='age')
models.py
class Contact(models.Model):
Name = models.CharField(max_length=100)
Birthdate = models.DateField(default=datetime.now())
age = models.IntegerField(default=0)
def save(self, *args, **kwargs):
if self.Birthdate > date.today():
raise ValidationError("The date cannot be in the future!")
super(Contact, self).save(*args, **kwargs)
@property
def age(self):
today = date.today()
birth = self.Birthdate
newage = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
return newage
def __str__(self):
return self.Name
views.py
class ContactList(generics.ListCreateAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
class ContactDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
Answers:
You can try to_representation() method to display your attributes in a nested json under another attribute.
For this you have to edit your views.py by adding to_representation() method in this order:
class ContactSerializer(serializers.ModelSerializer):
Name = serializers.CharField(max_length=100)
Birth_year = serializers.IntegerField(default=2022)
class Meta:
model = Contact
fields = ('Name','Birthdate','age')
def to_representation(self, instance):
response = {
"set_attributes" : super().to_representation(instance),
}
return response
class ListingSerializer(serializers.ModelSerializer):
age = serializers.Field(source='age')
Implementing the .to_representation(self, value) method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.
This is the output:
{ "set_attributes" :
{
"name": "some value",
"Birthdate": 2005/4/24,
"age": 17
},
}
Hope it helped.
I am new to Django APIs. I am designing a api where response will be like this after a post request:
{ "set_attributes":
{
"name": "some value",
"age": "another value"
},
}
At present my response showing like this:
{
"Name": "some value",
"age": "another value"
}
I am using class based views and for forms I am using Django models. I did not render any html forms.
serializers.py:
class ContactSerializer(serializers.ModelSerializer):
Name = serializers.CharField(max_length=100)
Birthdate = serializers.DateField(default=datetime.now())
class Meta:
model = Contact
fields = ('Name', 'Birthdate', 'age')
class ListingSerializer(serializers.ModelSerializer):
age = serializers.Field(source='age')
models.py
class Contact(models.Model):
Name = models.CharField(max_length=100)
Birthdate = models.DateField(default=datetime.now())
age = models.IntegerField(default=0)
def save(self, *args, **kwargs):
if self.Birthdate > date.today():
raise ValidationError("The date cannot be in the future!")
super(Contact, self).save(*args, **kwargs)
@property
def age(self):
today = date.today()
birth = self.Birthdate
newage = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
return newage
def __str__(self):
return self.Name
views.py
class ContactList(generics.ListCreateAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
class ContactDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
You can try to_representation() method to display your attributes in a nested json under another attribute.
For this you have to edit your views.py by adding to_representation() method in this order:
class ContactSerializer(serializers.ModelSerializer):
Name = serializers.CharField(max_length=100)
Birth_year = serializers.IntegerField(default=2022)
class Meta:
model = Contact
fields = ('Name','Birthdate','age')
def to_representation(self, instance):
response = {
"set_attributes" : super().to_representation(instance),
}
return response
class ListingSerializer(serializers.ModelSerializer):
age = serializers.Field(source='age')
Implementing the .to_representation(self, value) method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.
This is the output:
{ "set_attributes" :
{
"name": "some value",
"Birthdate": 2005/4/24,
"age": 17
},
}
Hope it helped.