[英]How can I convert my json response to nested json where attributes are under another 'attribute'?
我是 Django API 的新手。 我正在設計一個 api ,在發布請求后響應將是這樣的:
{ "set_attributes":
{
"name": "some value",
"age": "another value"
},
}
目前我的回復顯示如下:
{
"Name": "some value",
"age": "another value"
}
我正在使用基於 class 的視圖,對於 forms,我正在使用 Django 模型。 我沒有渲染任何 html forms。
序列化程序.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')
模型.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
視圖.py
class ContactList(generics.ListCreateAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
class ContactDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
您可以嘗試 to_representation() 方法在另一個屬性下的嵌套 json 中顯示您的屬性。
為此,您必須按以下順序添加 to_representation() 方法來編輯您的views.py:
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')
實現 .to_representation(self, value) 方法將字段的目標作為值參數,並且應該返回應該用於序列化目標的表示。 value 參數通常是 model 實例。
這是 output:
{ "set_attributes" :
{
"name": "some value",
"Birthdate": 2005/4/24,
"age": 17
},
}
希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.