Django -Как сделать доступным для записи несколько полей сериализаторов? - PullRequest
0 голосов
/ 12 февраля 2020

Я пытаюсь создать вложенный сериализатор, используя DJANGO REST FRAMEWORK.

Но я не знаю, как использовать методы создания обновлений в serializer.py. Я уже создал модели и некоторые работающие сериализаторы. И я хочу, чтобы весь этот сериализатор был доступен для записи и редактирования, но я не знаю, как это сделать, я пытался, но не смог получить реальный результат. Вот мой код.

from rest_framework import serializers
from ..models import about, education, work, project, skill, language, hobbies, techonogies
from django.contrib.auth.models import User
# from drf_writable_nested.serializers import WritableNestedModelSerializer


class EducationSerializer(serializers.ModelSerializer):
    class Meta:
        model = education
        exclude = ['about','created_by']


class WorkSerializer(serializers.ModelSerializer):
    class Meta:
        model = work
        exclude = ['about','created_by']



class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = project
        exclude = ['about','created_by']


class LanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = language
        exclude = ['about','created_by']

class SkillSerializer(serializers.ModelSerializer):
    class Meta:
        model = skill
        exclude = ['about','created_by']


class HobbiesSerializer(serializers.ModelSerializer):
    class Meta:
        model = hobbies
        exclude = ['about','created_by']

class TechSerializer(serializers.ModelSerializer):

    class Meta:
        model = techonogies
        exclude = ['about','created_by']


class PersonalSerializers(serializers.ModelSerializer):
        class Meta:
            model = about
            exclude = ['user']

        def create(self, validated_data):
            validated_data['user'] = self.context['request'].user
            return super().create(validated_data)

class AaProfileSerializer(PersonalSerializers):
    educations = EducationSerializer(many=True,  required=False)
    works = WorkSerializer(many=True,  required=False)
    projects = ProjectSerializer(many=True,  required=False)
    languages = LanguageSerializer(many=True,  required=False)
    skills = SkillSerializer(many=True,   required=False)
    hobbie = HobbiesSerializer(many=True,  required=False)
    tech = HobbiesSerializer(many=True,  required=False)

    def create(self, validated_data):
        if 'educations' in validated_data:
            es = validated_data.pop('educations')
        else:
            es = []

        if 'works' in validated_data:
            cds = validated_data.pop('works')
        else:
            cds = []

        if 'projects' in validated_data:
            prs = validated_data.pop('projects')
        else:
            prs = []

        if 'languages' in validated_data:
            ls = validated_data.pop('languages')
        else:
            ls = []

        if 'skills' in validated_data:
            ss = validated_data.pop('skills')
        else:
            ss = []

        if 'hobbie' in validated_data:
            hs = validated_data.pop('hobbie')
        else:
            hs = []

        if 'tech' in validated_data:
            ts = validated_data.pop('tech')
        else:
            ts = []

        instance = super().create(validated_data)

        for ndata in es:
            # if 'date' not in ndata:
            #     ndata['date'] = date.today()
            instance.educations.create( **ndata) #created_by=self.context['request'].user,

        for cd in cds:
            instance.works.create(**cd)

        for cd in prs:
            instance.projects.create(**cd)

        for cd in ls:
            instance.languages.create(**cd)

        for cd in ss:
            instance.skills.create(**cd)

        for cd in hs:
            instance.hobbie.create(**cd)

        for cd in ts:
            instance.tech.create(**cd)


        return instance

    # def update(self, instance, validated_data):
    #     if 'education_set' in validated_data:
    #         for ndata in validated_data['education_set']:
    #             print('NDATA', ndata)
    #             if ndata.get('id'):
    #                 note = instance.education_set.get(id=ndata['id'])
    #                 ndata.pop('id')
    #             else:
    #                 note = education(about=instance, created_by=self.context['request'].user)
    #             for k, v in ndata.items():
    #                 setattr(note, k, v)
    #             #note.save()
    #         validated_data.pop('education_set')

    #     if 'work_set' in validated_data:
    #         for ndata in validated_data['work_set']:
    #             if ndata.get('id'):
    #                 note = instance.cardriver_set.get(id=ndata['id'])
    #             else:
    #                 note = work(about=instance)
    #             for k, v in ndata.items():
    #                 setattr(note, k, v)
    #             #note.save()
    #         validated_data.pop('work_set')


    #     return super().update(instance, validated_data)



class AboutSerializers(AaProfileSerializer):
    educations = EducationSerializer(many=True, source='education_set' ,write_only=True, required=False)
    works = WorkSerializer(many=True, source='work_set' ,write_only=True, required=False)
    projects = ProjectSerializer(many=True, source='project_set' ,write_only=True, required=False)
    languages = LanguageSerializer(many=True, source='language_set' , write_only=True, required=False)
    skills = SkillSerializer(many=True,  source='skill_set' ,write_only=True, required=False)
    hobbie = HobbiesSerializer(many=True, source='hobbie_set' , write_only=True, required=False)
    tech = HobbiesSerializer(many=True,write_only=True, source='tech_set' , required=False)


    class Meta:
        model = about
        fields = "__all__"



class ViewSerializers(serializers.ModelSerializer):
    educations = EducationSerializer(many=True)
    works = WorkSerializer(many=True)
    projects = ProjectSerializer(many=True)
    languages = LanguageSerializer(many=True)
    skills = SkillSerializer(many=True)
    hobbie = HobbiesSerializer(many=True)
    tech = HobbiesSerializer(many=True)
    user = serializers.SerializerMethodField()

    class Meta:
        model = about
        fields = ["pk","user","image","name","location","github","phone","email","web","linkedin","skype","about","education","work","project","language","skill","hobbies","technologies","other","educations","works","projects","languages","skills","hobbie","tech","educations","works","projects","languages","skills","hobbie","tech"]

    def get_user(self, obj):
        return obj.user.username

И educations, works, projects, languages, skills, hobbie, tech это все связанные названия_ моделей

...