我无法序列化多个对象as this answers says to do。特别是,当尝试在序列化程序Functional
上获取字段GeneralSerializer
的值时,它给了我这个错误“ Got AttributeError。
序列化程序字段的名称可能不正确,并且与QuerySet
实例上的任何属性或键都不匹配。
原始异常文本为:'QuerySet'对象没有属性'Functional'。”
有人可以帮助我吗?
我的views.py
就是这样
General = namedtuple('General', ('Functional', 'Pfm'))
@csrf_exempt
def listall(request):
if request.method == 'GET':
general = General(
Functional= SnpsFunctionalelement.objects.values('countexperiments','filetype',rsid=F('snpid__rsid'), FunctionalElement=F('elementid__name'), CellLine=F('celllineid__name')),
Pfm = SnpsPfm.objects.values('start','strand','type','scoreref','scorealt',rsid=F('snpid__rsid'), pfm_name=F('pfmid__name'))
)
serializer = GeneralSerializer(general, many = True)
return JsonResponse(serializer.data, safe=False)
我的serializers.py
class SnpsFunctionalelementSerializer(serializers.ModelSerializer):
rsid = serializers.CharField(max_length=20)
FunctionalElement = serializers.CharField(max_length=55)
CellLine = serializers.CharField(max_length=55)
class Meta:
model = SnpsFunctionalelement
fields = ['rsid', 'FunctionalElement', 'CellLine', 'countexperiments', 'filetype']
class SnpsPfmSerializer(serializers.ModelSerializer):
rsid = serializers.CharField(max_length=20)
pfm_name = serializers.CharField(max_length=50)
class Meta:
model = SnpsPfm
fields =[ 'rsid','pfm_name','start','strand','type','scoreref','scorealt']
class GeneralSerializer(serializers.Serializer):
Functional = SnpsFunctionalelementSerializer(many=True)
Pfm = SnpsPfmSerializer(many=True)
P.S .:我什至尝试在没有DRF序列化程序执行此操作的情况下
all_objects = [SnpsFunctionalelement.objects.values('countexperiments','filetype',rsid=F('snpid__rsid'), FunctionalElement=F('elementid__name'), CellLine=F('celllineid__name')),
SnpsPfm.objects.values('start','strand','type','scoreref','scorealt',rsid=F('snpid__rsid'), pfm_name=F('pfmid__name'))]
ser = serializers.serialize('json',all_objects)
return JsonResponse(ser)
但是它给了我这个错误“ QuerySet
对象没有属性_meta
”