gpt4 book ai didi

python - 按模型创建记录

转载 作者:搜寻专家 更新时间:2023-10-30 20:14:11 24 4
gpt4 key购买 nike

假设我有这样的模型:

class Recipe (models.Model):
par_recipe = models.CharField(max_length=200)

class Line (models.Model):
par_machine = models.CharField(max_length=200)

class Measurements (models.Model):
par_value = models.IntegerField(default=0)
id_line = models.ForeignKey(Line)
id_recipe = models.ForeignKey(Recipe)

我是否理解正确,通过这种方式我有一个 1:1 关系,并且添加条目 id 将自动创建 id_line,id_recipe

我将添加例如:

for row in ws.iter_rows(row_offset=1):
recipe =Recipe()
line = line()
measurements = Measurements()

recipe.par_recipe = row[1].value
line.par_machine = row[2].value
measurements.par_value = row[8].value

关于测量的小问题被设想为所有辅助键都应该去它,现在它正确实现了吗?

最佳答案

不是那样的,你必须把它们绑在一起:

for row in ws.iter_rows(row_offset=1):
recipe =Recipe.objects.create(par_recipe=row[1].value)
line = Line.objects.create(par_machine=row[2].value)
measurements = Measurements.objects.create(
par_value=row[8].value,
id_line=line,
id_recipe=recipe
)

这些都不是数据库优化的,您可以使用事务来优化数据库写入。

如果有很多行,你可以通过使用事务使它更快:

from django.db import transaction

with transaction.atomic():
for row in ws.iter_rows(row_offset=1):
recipe =Recipe.objects.create(par_recipe=row[1].value)
line = Line.objects.create(par_machine=row[2].value)
measurements = Measurements.objects.create(
par_value=row[8].value,
id_line=line,
id_recipe=recipe
)

这将创建一个事务并写入一个而不是每次。但它也会因错误而导致整个交易失败。

参见 Django Database Transactions

您可以通过计算记录数并每 1000 条记录写入一次来获得更多创意,例如:

from django.db import transaction

with transaction.atomic():
for idx, row in enumerate(ws.iter_rows(row_offset=1)):
recipe =Recipe.objects.create(par_recipe=row[1].value)
line = Line.objects.create(par_machine=row[2].value)
measurements = Measurements.objects.create(
par_value=row[8].value,
id_line=line,
id_recipe=recipe
)
# every 1000 records, commmit the transaction
if idx % 1000 == 0:
transaction.commit()

关于python - 按模型创建记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53579234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com