Проверка в случае сериализатора нескольких объектов - PullRequest
0 голосов
/ 10 апреля 2020

Мои данные вводятся в виде списка 'n' числа диктов

"contact_person":[
               {
                   "contactperson_salutation[0]":"sddd",
                   "contactperson_first_name[0]":"santoorr",
                   "contactperson_last_name[0]":"",
                   "contactperson_email[0]":"gfgh",
                   "contactperson_mobile_number[0]":"",
                   "contactperson_work_phone_number[0]":"jio"
               },
               {
                   "contactperson_salutation[1]":"dfsf",
                   "contactperson_first_name[1]":"lux",
                   "contactperson_last_name[1]":"",
                   "contactperson_email[1]":"",
                   "contactperson_mobile_number[1]":"",
                   "contactperson_work_phone_number[1]":"9048"
               }, .............]

Моя модель такая:

class ContactPerson(models.Model):

   client = models.ForeignKey(Client, on_delete=models.CASCADE)
   contactperson_salutation = models.CharField(max_length=4, choices=SALUTATIONS)
   contactperson_first_name = models.CharField(max_length=128)
   contactperson_last_name = models.CharField(max_length=128, blank=True)
   contactperson_email = models.EmailField(blank=True, null=True)
   contactperson_mobile_number = models.CharField(max_length=20, blank=True)
   contactperson_work_phone_number = models.CharField(max_length=20, blank=True)

Как написать сериализатор при полях имена меняются для каждого слова в списке ввода.

И если возникают ошибки, ответ об ошибке должен быть в следующем формате:

            [
                {
                    "contactperson_email[0]":"Invalid Email",
                    "contactperson_mobile_number[0]":"Invalid mobile phone",
                    "contactperson_work_phone_number[0]":"Invalid workphone number"
                },
                {
                    "contactperson_mobile_number[1]":"Invalid mobile phone",
                    "contactperson_work_phone_number[1]":"Invalid workphone number"
                }
             ]

Ответы [ 2 ]

0 голосов
/ 15 апреля 2020

попробуйте переписать метод to_internal_value в Сериализаторе, чтобы добиться этого.

Но ошибка все равно будет не в том формате, который вам нужен. В сообщении об ошибке будут содержаться ключи вашей модели, а не ключи с суффиксом [x].

class ContactPersonSerializer(serializers.ModelSerializer):

    class Meta:
        model = ContactPerson
        fields = [
        "contactperson_salutation",
        "contactperson_first_name",
        "contactperson_last_name",
        "contactperson_email",
        "contactperson_mobile_number",
        "contactperson_work_phone_number",
    ]

    def to_internal_value(self, data):
        if hasattr(data, "_mutable"):
            data._mutable = True

        data = {key[:-3]: value for key, value in data.items()}

        if hasattr(data, "_mutable"):
            data._mutable = False

        return super().to_internal_value(data)
0 голосов
/ 11 апреля 2020

Вы, вероятно, выиграете от разбора "contactperson_salutation[0]" -подобных строк для построения list contactperson_salutation со всеми вхождениями.

То же самое для каждого из других полей.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...