Answer the question
In order to leave comments, you need to log in
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"
},
]
}
]
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='Группа')
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
[
{
"usersDutyList": [
{
"group": [
"Обязательное поле."
]
}
]
},
{
"usersDutyList": [
{
"group": [
"Обязательное поле."
]
}
]
}
]
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question