DRF ViewSet返回带有空值的QuerySet

时间:2018-08-14 19:24:14

标签: django django-rest-framework django-rest-viewsets drf-queryset

我有一个称为“ QueryCriteriaViewSet”的DRF ViewSet,它在查询构建器中使用,它允许用户选择一个字段,然后从相关条件中选择。因此,例如,用户可以选择“ reg_status”字段,然后从相关标准“活动”和“非活动”中进行选择。

当我从主要的“人”模型中选择一个字段时,这完全可以正常工作。但是,当我从相关模型(例如“ lookup_party”模型)中选择一个字段时,我遇到了问题。但是,很奇怪的是,当我将查询集打印到控制台时,它可以正常运行,但是当我调用API时,它返回了一个空对象列表。

再举一个例子,当我打电话时会发生以下情况:

api/querycriteria/?fields=reg_status返回:

[
    {"reg_status": "Active"}, 
    {"reg_status": "Inactive"}
]

api/querycriteria/?fields=party__party_name返回时:

[
    {},
    {},
    {},
    {},
    {}
]

即使我在返回查询集之前print(queryset),也会打印以下内容:

<QuerySet [{'party__party_name': None}, {'party__party_name': 'Democratic'}, 
{'party__party_name': 'Non-Partisan'}, {'party__party_name': 'Registered 
Independent'}, {'party__party_name': 'Republican'}]>

这是完整的ViewSet:

class QueryCriteriaViewSet(DefaultsMixin, viewsets.ModelViewSet):
    serializer_class = QueryCriteriaSerializer

    def get_queryset(self):
        fields = self.request.GET.get('fields', None)
        queryset = Person.objects.values(fields).distinct()
        print(queryset)
        return queryset

    def get_fields_to_display(self):
        fields = self.request.GET.get('fields', None)
        return fields.split(',') if fields else None

    def get_serializer(self, instance=None, data=empty, many=False,
                       partial=False):
        """
        Return the serializer instance that should be used for validating and
        deserializing input, and for serializing output.
        """
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        fields = self.get_fields_to_display()
        return serializer_class(instance, data=data,
                                many=many, partial=partial,
                                context=context, fields=fields)

让我知道是否有任何其他信息会有所帮助。

这是我的序列化器:

from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.reverse import reverse
from ..models.people import Person
from ..models.people_emails import Email
from ..models.people_addresses import Address
from ..models.people_phones import Phone
from ..models.people_tags import PersonTag
from ..models.people_elections import PersonElection
from ..models.people_districts import PersonDistrict
from ..models.people_attributes import Attribute
from .serializer_dynamic_fields import DynamicFieldsModelSerializer
from .serializer_tag import TagSerializer
from .serializer_email import EmailSerializer
from .serializer_address import AddressSerializer
from .serializer_phone import PhoneSerializer
from .serializer_election import ElectionSerializer
from .serializer_attribute import AttributeSerializer
from .serializer_district import DistrictSerializer

class QueryCriteriaSerializer(DynamicFieldsModelSerializer):

    emails = EmailSerializer(many=True, required=False)
    addresses = AddressSerializer(many=True, required=False)
    phones = PhoneSerializer(many=True, required=False)
    tags = TagSerializer(many=True, required=False)
    elections = ElectionSerializer(many=True, required=False)
    attributes = AttributeSerializer(many=True, required=False)
    districts = DistrictSerializer(many=True, required=False)

    class Meta:
        model = Person
        fields = ('id', 'elected_official', 'title', 'first', 'last', 'middle',    'suffix',
        'full_name', 'birthdate', 'sex', 'website', 'deceased', 'registered',    'party',
        'reg_date', 'reg_status', 'reg_state', 'county', 'match_id',
        'date_added', 'date_updated', 'do_not_call', 'do_not_mail',    'do_not_email', 'do_not_text', 'emails',
        'addresses', 'phones', 'tags', 'attributes', 'elections', 'districts')

这是DynamicFieldsModelSerializer:

from django.contrib.auth import get_user_model
from rest_framework import serializers

class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)

        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        if fields is not None:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

1 个答案:

答案 0 :(得分:0)

现在发现问题了,只有传递给它的字段是序列化器原始字段的子集时,DynamicFieldsModelSerializer才起作用。

您应该以一种可以接受额外字段的方式使用序列化程序,如下所示:

class ExtraDynamicFieldsModelSerializer(serializers.ModelSerializer):


    def __init__(self, *args, **kwargs):
        extra_fields = kwargs.pop('fields', [])
        self.extra_fields = set()
        # Instantiate the superclass normally
        super(ExtraDynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        allowed = set(extra_fields)
        existing = set(self.fields)
        for field_name in existing - allowed:
            self.fields.pop(field_name)

        for field_name in allowed - existing:
            self.extra_fields.add(field_name)



    def to_representation(self, obj):
        data = super().to_representation(obj)
        for field in self.extra_fields:
            data[field] = obj[field]
        return data