使用ChoiceField时,Django Rest API TypeError

时间:2017-07-26 03:50:04

标签: python django django-rest-framework

我尝试在序列化程序中使用TypeError时遇到ChoiceField

from rest_framework import serializers
from rest_framework.fields import ChoiceField

from comp_track_sys.models import Campaign
from contacts.models import CList

class EditCampaignSerializer(serializers.ModelSerializer):
    class Meta:
        model = Campaign
        ...

    def __init__(self, *args, **kwargs):
        super(EditCampaignSerializer, self).__init__(*args, **kwargs)
        user = self.context['request'].user
        clists = CList.objects.filter(company=user.profile.company)
        self.fields['clist'] = ChoiceField(choices=clists)

我曾尝试ChoiceField(choices=json.dumps(clists)),但仍然遇到错误。

TypeError: <CList: Testing> is not JSON serializable

这些是我的模型,以防需要解决问题。

# Campaign Model
class Campaign(models.Model):
    campaign_id = UUIDField(auto=True)
    name = models.CharField("Campaign Name", max_length=50)
    company = models.ForeignKey(Company)
    clist = models.ForeignKey(CList, verbose_name="Contact List", blank=True, null=True)
    user = models.ForeignKey(User, blank=True, null=True)

# CList Model
class CList(models.Model):
    name = models.CharField("Contact List", max_length=255)
    description = models.TextField(blank=True, null=True)
    contacts = models.ManyToManyField(Contact, related_name='con_clists')
    company = models.ForeignKey(Company)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    uuid = models.CharField("ShortUUID", max_length=50, blank=True, null=True)

这是观点

class EditCampaignViewSet(ModelViewSet):
    queryset = Campaign.objects.all()
    serializer_class = EditCampaignSerializer
    parser_classes = (MultiPartParser, FormParser)

    def list(self, request, type=None, *args, **kwargs):
        company = request.user.company
        queryset = Campaign.objects.filter(company=company,
                                           campaign_type=type)\
                                   .order_by('-created')\
                                   .prefetch_related('user__profile')
        serializer = EditCampaignSerializer(queryset, many=True, context={'request': self.request})
        return Response(serializer.data)

2 个答案:

答案 0 :(得分:3)

我认为您应该使用PrimaryKeyRelatedField而不是ChoiceField,并在序列化工具字段中定义自定义get_queryset方法来过滤相关的QuerySet

from rest_framework import serializers
from rest_framework.fields import ChoiceField

from comp_track_sys.models import Campaign
from contacts.models import CList

class CListPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):

    def get_queryset(self):
        return self.queryset.filter(
           company=self.root.context['request'].user.profile.company
        )

class EditCampaignSerializer(serializers.ModelSerializer):

    clist = CListPrimaryKeyRelatedField(
        queryset=CList.objects.all(),
    )

    class Meta:
        model = Campaign
        fields = (
            'clist',
        )

答案 1 :(得分:1)

创建ChoiceField时,您需要确保choices关键字是可迭代的。通过使用json.dumps(clists),我想您正在尝试将clists转换为可迭代,但CList类型无法进行JSON序列化,因为json库无法识别它。

选择要设置为有效选项的字段后,您可以尝试这样的操作,例如,如果您要选择的字段是主键:

ChoiceField(choices=list(clists.values_list('pk', flat=True)))

由于.values_list方法返回一个iterable,因此可以传递给choices=

希望我帮助过。