我有,在models.py:
class Bedrooms_types(models.Model):
bedrooms_type = models.CharField(max_length=100)
def __str__(self): # __unicode__ on Python 2
return self.bedrooms_type
class Meta:
ordering = ('bedrooms_type',)
class Buildings(models.Model):
name = models.CharField(max_length=300)
category=models.CharField(max_length=200)
type=models.CharField(max_length=200)
bedrooms_types = models.ManyToManyField(Bedrooms_types)
bedrooms = models.CharField(max_length=200,blank=True)
owner = models.CharField(max_length=200,blank=True)
construction_date = models.DateField(null=True,blank=True)
def __str__(self): # __unicode__ on Python 2
return self.name
class Meta:
ordering = ('name',)
并在serializers.py中:
class BuildingSerializer(serializers.ModelSerializer):
bedrooms_types = serializers.RelatedField(many=True)
当我加载网址/building/
时,我得到:
[{"bedrooms_types": ["grande-suite", "junior-suite"], "id": 1, "name": "Hilton", "category": "hotel", "type": "4-star", "bedrooms": "100", "owner": "", "construction_date": null}]
字段卧室,construction_date和所有者可以为空。如何更改serializer.py以在这些字段为空时不显示这些字段?
对于这个例子,我想得到:
[{"bedrooms_types": ["grande-suite", "junior-suite"], "id": 1, "name": "Hilton", "category": "hotel", "type": "4-star", "bedrooms": "100", "}]
答案 0 :(得分:1)
以下是我的回答:
from collections import OrderedDict
from rest_framework import serializers
from .models import Buildings
EMPTY_VALUES = ('', None, [], ())
class BuildingSerializer(serializers.ModelSerializer):
bedrooms_types = serializers.RelatedField(many=True)
class Meta:
model = Buildings
def get_fields(self):
fields = super(BuildingSerializer, self).get_fields()
return OrderedDict(
((name, field) for name, field in fields.iteritems()
if getattr(self.object, name) not in EMPTY_VALUES)
)
答案 1 :(得分:1)
您可以覆盖to_representation
以清理序列化模型
class ModelSerializer(serializers.ModelSerializer):
def to_representation(self, value):
repr_dict = super(ModelSerializer, self).to_representation(value)
return OrderedDict((k, v) for k, v in repr_dict.items()
if v not in [None, [], '', {}])