我有一个问题希望你们帮助我。我想要一个带有用户字段的ChoiceField choices=
参与者并且last_name为'Z'的用户。
我的序列化器:
class ArticleCreateSerializer(ModelSerializer):
user_choice = SerializerMethodField()
user = ChoiceField(choices=user_choice)
class Meta:
model = Feed
fields = [
'id',
'user',
'post',
'participants'
]
def get_user_choice(self, obj):
user_choice = User.objects.filter(id=obj.participants, last_name='Z')
return user_choice
错误:
TypeError: 'SerializerMethodField' object is not iterable
答案 0 :(得分:1)
试试这个,
class ArticleCreateSerializer(ModelSerializer):
def get_user_choice():
user_choice = User.objects.filter(id=obj.participants, last_name='Z').values_list('username',flat=True)
return user_choice
user = ChoiceField(choices=get_user_choice())
class Meta:
model = Feed
fields = [
'id',
'user',
'post',
'participants'
]