gpt4 book ai didi

python - 使用 ChoiceField 时 Django Rest API TypeError

转载 作者:行者123 更新时间:2023-11-28 22:25:47 25 4
gpt4 key购买 nike

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

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)

最佳答案

我认为您应该使用 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',
)

关于python - 使用 ChoiceField 时 Django Rest API TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45317114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com