Django:选择多个随机ID并插入数据库

问题描述 投票:0回答:1

我正在生成时间表,它会自动从 RoutePoint 类中选择。我想发布所有这些 id 并根据用户想要的 id 数量创建行数。

这就是我选择随机 id 的方法。但它显示

RoutePoints object (3)

no_of_route = request.POST.get('time')

items = list(RoutePoints.objects.all())
random_route = random.sample(items, no_of_route)[0]

所以问题是,我不知道如何插入这些id。喜欢批量插入吗?如果用户选择 3

no_of_route
,则应在“Schedule”表中插入 3 行。

Schedule.objects.create(route=random_route, report_time=report_time)

这是我第一次,所以我不知道到底该怎么做。谢谢您的帮助。

python mysql django
1个回答
0
投票

你可以使用Django的bulk_create方法一次性创建多个对象。

from django.db import transaction

no_of_route = int(request.POST.get('time'))  # make sure to convert to int
items = list(RoutePoints.objects.all())
random_routes = random.sample(items, no_of_route)

schedules_to_create = []
for route in random_routes:
    schedule = Schedule(route=route, report_time=report_time)
    schedules_to_create.append(schedule)

with transaction.atomic():
    Schedule.objects.bulk_create(schedules_to_create)

在此代码中,random.sample(items, no_of_route) 将返回 no_of_route 数量的随机 RoutePoints 对象的列表。然后,使用列表推导式创建 Schedule 对象列表(不将它们保存到数据库)。最后,Schedule.objects.bulk_create(schedules) 用于在单个查询中将所有 Schedule 对象保存到数据库。

© www.soinside.com 2019 - 2024. All rights reserved.