Я пытаюсь обновить вложенный сериализатор, он выдает ошибку. Paper_description с таким идентификатором уже существует? - PullRequest
0 голосов
/ 20 сентября 2019

Django Rest Framework вставка и обновление записываемого вложенного сериализатора. Я пытаюсь вставить и обновить записываемый вложенный сериализатор с помощью Django Rest Framework, как показано в следующих примерах.Но это не работает.

Что я мог сделать не так?

Контроллер

class JobCardViewSet(ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = JobCardSerializer
    http_method_names = ('get', 'post', 'put', 'patch')

    def get_queryset(self):
        if 'key' in self.request.GET:
            key = self.request.GET['key']
            return JobCard.objects.filter(models.Q(job_order_no__icontains=key) | models.Q(job_name__icontains=key))

        if 'party' in self.request.GET:
            return JobCard.objects.filter(party_name__name__icontains=self.request.GET['party'])

        else:
            return JobCard.objects.all()

    def create(self, request, *args, **kwargs):
       self.serializer_class = JobCardPostSerializer
       return super(JobCardViewSet, self).create(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):
        self.serializer_class = JobCardPostSerializer
        return super(JobCardViewSet, self).update(request, *args, **kwargs)

Сериализатор

Мой сериализатор

    class PaperDescriptionPostSerializer(ModelSerializer):
        class Meta:
            model = PaperDescription
            fields = '__all__'

     class JobCardPostSerializer(ModelSerializer):
         paper_description = PaperDescriptionPostSerializer(many=True)

         class Meta:
             model = JobCard
             fields = '__all__'


def create(self, validated_data):
    paper_description_list = validated_data.pop('paper_description')
    job_card = JobCard.objects.create(**validated_data)
    for paper in paper_description_list:
        paper.update({"party_name": job_card.party_name})
        paper.update({"job_order_no": job_card.job_order_no})
        paper.update({"job_name": job_card.job_name})
        paper.update({"job_date": job_card.job_date})
        paper.update({"job_type": job_card.job_type})
        job_card.paper_description.add(PaperDescription.objects.create(**paper))

    return job_card

def update(self, instance, validated_data):
    paper_description = validated_data.pop('paper_description')
    instance.job_name = validated_data.get("job_name", instance.job_name)
    instance.job_date = validated_data.get("job_date", instance.job_date)
    instance.delivery_date = validated_data.get("delivery_date", instance.delivery_date)
    instance.job_created_by = validated_data.get("job_created_by", instance.job_created_by)
    instance.die_no = validated_data.get("die_no", instance.die_no)
    instance.job_re_print = validated_data.get("job_re_print", instance.job_re_print)
    instance.remarks = validated_data.get("remarks", instance.remarks)
    instance.update_reason = validated_data.get("update_reason", instance.update_reason)
    instance.job_details = validated_data.get("job_details", instance.job_details)
    instance.party_name = validated_data.get("party_name", instance.party_name)
    instance.reference_id = validated_data.get("reference_id", instance.reference_id)
    instance.branch_name = validated_data.get("branch_name", instance.branch_name)

    # instance.title = validated_data.get("title", instance.title)

    instance.save()
    keep_id = []
    for choice in paper_description:
        if "id" in choice.keys():
            if PaperDescription.objects.filter(id=choice["id"]).exists():
                c = PaperDescription.objects.get(id=choice["id"])
                # c.text = choice.get('text', c.text)
                c.job_name = choice.get('job_name', c.job_name)
                c.job_date = choice.get('job_date', c.job_date)
                c.job_element = choice.get('job_element', c.job_element)
                c.thickness = choice.get('thickness', c.thickness)
                c.no_of_pages = choice.get('no_of_pages', c.no_of_pages)
                c.print_size = choice.get('print_size', c.print_size)
                c.order_qty = choice.get('order_qty', c.order_qty)
                c.no_of_ups = choice.get('no_of_ups', c.no_of_ups)
                c.print_sheets = choice.get('print_sheets', c.print_sheets)
                c.forms = choice.get('forms', c.forms)
                c.no_of_plates = choice.get('no_of_plates', c.no_of_plates)
                c.wastage_per_farma = choice.get('wastage_per_farma', c.wastage_per_farma)
                c.front_color = choice.get('front_color', c.front_color)
                c.double_single = choice.get('double_single', c.double_single)
                c.total_wastage = choice.get('total_wastage', c.total_wastage)
                c.paper_required = choice.get('paper_required', c.paper_required)
                c.back_color = choice.get('back_color', c.back_color)
                c.prints = choice.get('prints', c.prints)
                c.ruling = choice.get('ruling', c.ruling)
                c.party_name = choice.get('party_name', c.party_name)
                c.paper_type = choice.get('paper_type', c.paper_type)
                c.paper_size = choice.get('paper_size', c.paper_size)
                c.paper_brand = choice.get('paper_brand', c.paper_brand)
                c.machine_name = choice.get('machine_name', c.machine_name)

                c.save()
                keep_id.append(c.id)
            else:
                continue
        else:
            c = PaperDescription.objects.create(**choice)
            keep_id.append(c.id)

    for choice in instance.paper_description:
        if choice.id not in keep_id:
            choice.delete()

    return instance

Ошибка

При обновлении вложенный объект с идентификатором уже существует

{
    "paper_description": [
        {
            "id": [
                "paper description with this id already exists."
            ]
        },
        {
            "id": [
                "paper description with this id already exists."
            ]
        }
    ]
}
...