H
H
HELLSP4RK2021-06-22 14:17:53
Django
HELLSP4RK, 2021-06-22 14:17:53

How to create multiple related objects from JSON?

There is a JSON like this:

[
  {
    "groupId": 123,
    "groupName": "Group 1",
    "monthName": "Май",
    "monthNumber": 5,
    "year": 2021,
    "usersDutyList": [
      {
        "userName": "Test",
        "userFullname": "Test User",
        "userId": 553,
        "userEmail": "[email protected]",
        "isOnDutyThisMonth": true,
        "userPhone": "+1 234 5678",
        "userExt": "123",
        "isOwner": "false"
      },
      {
        "userName": "Test2",
        "userFullname": "Test2 User",
        "userId": 458,
        "userEmail": "[email protected]",
        "isOnDutyThisMonth": true,
        "userPhone": "+1 234 5678",
        "userExt": "321",
        "isOwner": "false"
      },
    ]
  }
]


I wrote these models:
class Group(Model):
    groupId = SmallIntegerField(primary_key=True, verbose_name='ID группы')
    groupName = CharField(max_length=100, verbose_name='Наименование')
    monthName = CharField(max_length=8, choices=MONTH_NAME_CHOICES, verbose_name='Название месяца')
    monthNumber = SmallIntegerField(choices=MONTH_NUMBER_CHOICES, verbose_name='Номер месяца')
    year = SmallIntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year)

class User(Model):
    userName = CharField(max_length=20, unique=True, verbose_name='Логин')
    userFullname = CharField(max_length=40, verbose_name='ФИО')
    userId = SmallIntegerField(primary_key=True, verbose_name='ID пользователя')
    userEmail = EmailField(unique=True, verbose_name='Email')
    userPhone = CharField(max_length=15, verbose_name='Номер телефона')
    userExt = CharField(max_length=10, verbose_name='Добавочный')
    isOwner = BooleanField(verbose_name='Руководитель группы')
    group = ForeignKey(Group, on_delete=CASCADE, related_name='usersDutyList', verbose_name='Группа')


I need to create an object of the Group model and the users associated with it from the usersDutyList key from this JSON.

Wrote the following serializers:
class UserSerializer(HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = '__all__'


class GroupSerializer(HyperlinkedModelSerializer):
    usersDutyList = UserSerializer(many=True, required=False)

    def create(self, validated_data):
        users = validated_data.pop('usersDutyList')
        group = Group.objects.create(**validated_data)
        for user in users:
            user_dict = dict(user)
            User.objects.create(group=group.groupId, **user_dict)
        return group


But since the group object is not passed to the UserSerializer serializer, I naturally get the answer
[
    {
        "usersDutyList": [
            {
                "group": [
                    "Обязательное поле."
                ]
            }
        ]
    },
    {
        "usersDutyList": [
            {
                "group": [
                    "Обязательное поле."
                ]
            }
        ]
    }
]


Can you please tell me how to implement this functionality?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Melnikov, 2021-06-22
@Mi11er

It is obligatory to do through DRF?
Why not just loop through and create objects?
The first object, groups, then a cycle of enumeration of users and their creation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question