django DRF: how to Get related model field in serializer

时间:2016-07-11 20:07:21

标签: python django serialization drf-nested-routers

I'm trying to return a HttpResponse from Django Rest Framework including data from 3 linked models. The models are

class ErrorDb(models.Model):
    error_id = models.AutoField(primary_key=True)
    error_msg = models.CharField(max_length=500)
    user_name = models.CharField(max_length=45)
    class Meta:
        #managed = False
        db_table = 'error_db'

class ErrordbKey(models.Model):
    key_id = models.AutoField(primary_key=True)
    parent_areaid = models.IntegerField(blank=True, null=True)

    class Meta:
        #managed = False
        db_table = 'errordb_key'


class ErrordbMapping(models.Model):
    table_id = models.AutoField(primary_key=True)
    key = models.ForeignKey(ErrordbKey)
    error = models.ForeignKey(ErrorDb)
    class Meta:
        #managed = False
        db_table = 'errordb_mapping'
        unique_together = (('key', 'error'),)

following is the views.py:

def area_detail(request, area_id):

obj_ErrordbKey = ErrordbKey.objects.filter(parent_areaid=area_id)
#objects to get specific rows where area_id exists

if request.method == 'GET':
    obj_ErrordbMapping = ErrordbMapping.objects.filter(key__in=obj_ErrordbKey)
    serializer = TaskSerializer(obj_ErrordbMapping, many=True)
    return Response(serializer.data)

I tried following serialization methods,please see the foeign key relation ship serializers.py:

class ErrorDbSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ErrorDb
        fields = ('error_msg','user_name')


class ErrordbKeySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ErrordbKey
        fields = ('area', 'filename')


class TaskSerializer(serializers.HyperlinkedModelSerializer):
    # errorDbdata = ErrorDbSerializer()
    # errordbKeydata = ErrordbKeySerializer()
    error = ErrorDbSerializer(source='error')
    key = ErrordbKeySerializer(source='key')
    class Meta:
        model = ErrordbMapping
        fields = ('key', 'error')

1 个答案:

答案 0 :(得分:2)

you can use source of serializer.CharField and access to field throw fk as usual:

class TaskSerializer(serializers.HyperlinkedModelSerializer):
    error_field = serializers.CharField(read_only=True, source='error.error_msg')
    key_field = serializers.CharField(read_only=True, source='key.parent_areaid')
    class Meta:
        model = ErrordbMapping
        fields = ('error_field', 'key_field')