我有两个模型District
和BTS
。我想得到像下面这样的回应。
[{
"id": 15,
"name": "Westen",
"page": 1,
"expanded": false,
"selected": false,
"children": [{
"id": 12,
"name": "BTS2",
"page": 1
}]
}, {
"id": 13,
"name": "Noth",
"page": 1,
"children": [{
"id": 13,
"name": "BTS2",
"page": 2
}]
}]
我有两个序列化器
class BTSSerializer(serializers.HyperlinkedModelSerializer):
def to_representation(self, value):
return {
'id': value.id,
'name': value.bts_id,
"page": 4,
"expanded": False,
"selected": False,
}
class Meta:
model = BTS
fields = ('bts_id', 'id')
class DistrictSerializer(serializers.HyperlinkedModelSerializer):
def to_representation(self, value):
return {
'id': value.id,
'name': value.name,
"page": 1,
"expanded": False,
"selected": False,
"children": []
}
class Meta:
model = District
fields = ('name', 'id')
这是BTS模型
class BTS(models.Model):
id = models.AutoField(primary_key=True)
bts_id = models.CharField(max_length = 100, unique=True)
district_id = models.ForeignKey(District, related_name='districts', on_delete=models.CASCADE, null=True)
bts_type_id = models.ForeignKey(BTSType, related_name='types', on_delete=models.CASCADE, null=True)
class Meta:
db_table = "base_stations"
def __str__(self):
return self.bts_id
我做了如下修改
class DistrictSerializer(serializers.HyperlinkedModelSerializer):
bts = BTSSerializer(many=True)
def to_representation(self, value):
return {
'id': value.id,
'name': value.name,
"page": 1,
"expanded": False,
"selected": False,
"children": value.bts
}
class Meta:
model = District
fields = ('name', 'id', 'bts')
我该如何实现?
收到此错误
AttributeError at /tree_parents/
'District' object has no attribute 'bts'
Request Method: GET
Request URL: http://localhost:8000/tree_parents/
Django Version: 2.2
Exception Type: AttributeError
Exception Value:
'District' object has no attribute 'bts'
Exception Location: /home/samitha/workspace/techlead/tas-test/api/serializers.py in to_representation, line 45
答案 0 :(得分:2)
最好查看您的District
模型,但是您可以尝试解决方案:
class DistrictSerializer(serializers.HyperlinkedModelSerializer):
children = BTSSerializer(source='districts', many=True)
num_children = serializers.SerializerMethodField()
page = serializers.SerializerMethodField()
expanded = serializers.SerializerMethodField()
selected = serializers.SerializerMethodField()
def get_page(self, obj):
return 1
def get_expanded(self, obj):
return False
def get_selected(self, obj):
return False
def get_num_children(self, obj):
return obj.districts.count()
class Meta:
model = District
fields = ('name', 'id', 'children', 'page', 'expanded', 'selected')