我正在尝试从 Django Rest Framework 返回一个 HttpResponse,包括来自 3 个链接模型的数据。模型是
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'),)
以下是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)
我尝试了以下序列化方法,请参阅 foeign 键关系船 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')