class ProfessionInfoSerializer(serializers.ModelSerializer):
class Meta:
model = ProfessionInfo
fields = ['profession', 'designation', 'description']
class UserProfileSerializer(serializers.ModelSerializer):
# use profession info from another serializer with many true
profession_info = ProfessionInfoSerializer(many=True)
class Meta:
model = UserProfile
fields = ['gender', 'birth_date', 'profession_info']
def update(self, instance, validated_data):
# remove profession_info before saving userProfile object.
profession_info_data = validated_data.pop('profession_info')
profession_info = []
for info_data in profession_info_data:
info, _ = ProfessionInfo.objects.get_or_create(**info_data)
profession_info.append(info)
instance.profession_info.set(profession_info)
return super().update(instance, validated_data)
1条答案
按热度按时间6tr1vspr1#
您可以在模型中添加其他
manytomany
字段,如下所示添加这些字段后,您可以在Django REST API中创建一个
serializer
,并使用您的用户数据获取专业数据,如下所示set
的参考:https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.set