-1

I have two models District and BTS. I want to get the response like bellow.

[{
    "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
    }]
}]

I have two Serializer

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')

This is BTS model

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

I changed as follows

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')

How could I achieve this ?

Got this error

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
6
  • django-rest-framework.org/api-guide/relations/… Commented Apr 25, 2019 at 6:16
  • i already followed that. when i add bts to field list it says bts is not in District Commented Apr 25, 2019 at 6:17
  • show the full Traceback, but if that is the case then error is self-explanatory, add bts to district, check the drf example again Commented Apr 25, 2019 at 6:24
  • @PetarP i updated the error . Commented Apr 25, 2019 at 6:35
  • You need add source='bts_set' Commented Apr 25, 2019 at 6:38

1 Answer 1

2

better to see your District model, but you can try the solution:

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')
Sign up to request clarification or add additional context in comments.

6 Comments

what is bts_set meanning ?
Got AttributeError when attempting to get a value for field children on serializer DistrictSerializer. The serializer field might be named incorrectly and not match any attribute or key on the District instance. Original exception text was: 'District' object has no attribute 'bts_set'. Request Method:
i hope a fixed, _set is default name for related objects docs.djangoproject.com/en/2.2/ref/models/relations/…, but you set the related_name so should be districts. Better to change it to the bts.
i works well. i want to get the children count to the parent object. how could i get it ?
create model property or serialized method
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.