按模型创建记录

时间:2018-12-02 10:06:43

标签: python django database

假设我有这样的模型:

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

关于测量的一个小问题被认为所有辅助键都应该交给它,现在它已正确实现了?

2 个答案:

答案 0 :(得分:3)

不是那样,您必须将它们绑在一起:

ls -a

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

如果使用事务,那么如果有很多行,则可以使其更快:

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 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
        )

答案 1 :(得分:2)

  

我是否正确理解以这种方式建立了1:1关系,并且添加条目ID会自动创建为id_line,id_recipe。

该关系将 not 链接到先前构造的对象,这也将是非常不安全的,因为对代码片段的微小更改可能会导致将元素链接在一起的方式完全不同。

此外,ForeignKey多对一关系:多个Measurements对象可以引用同一个Recipe对象。

您需要手动执行此操作,例如:

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
    )

请注意,ForeignKey是指对象,而不是主键值,因此您可能想重命名ForeignKey。模型通常具有一个单数名称,因此Measurement而不是Measurements

class Measurement(models.Model):
    par_value = models.IntegerField(default=0)
    line = models.ForeignKey(Line, on_delete=models.CASCADE)
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
相关问题