Django批量创建具有多个必填字段的模型

时间:2013-09-11 03:20:01

标签: django django-models

我有Person模型,Demographic模型和PersonDemographic模型,其中包含使用来自两个模型的数据的详细方法,并将一些非常昂贵的计算保存为特定字段人口统计实例。如何使用批量创建来方便我在PersonDemographic模型中输入?

class Person(models.Model):
    name = models.CharField(max_length=254)
    details = a bunch of fields ...

class Demographic(models.Model):
    name = models.CharField(max_length=254)
    details = a bunch of fields ...

class PersonDemographic(models.Model):
    person = models.ForeignKey(Person)
    demographic = models.ForeignKey(Demographic)
    expense_calc_property = models.FloatField(null=True)

    @property
    def random_property(self):
        calc using person/demographic details

    @property
    def expense_calc(self):
        if not expensive_calc_property:
           self.expensive_calc_property = results from expensive calc
           self.save()
        return self.expensive_calc_property               

那么如何将PersonDemographic.objects.bulk_create([])用于大型查询集,例如Person.object.some_query_set()与单个人口统计实例匹配,例如demographic = Demographic.objects.get(id=7)?换句话说,取代了:

demographic = Demographic.objects.get(id=7)
for person in Person.objects.some_query_set():
    pg = PersonDemographic.objects.create(person=person, demographic=demographic)
    pg.save()

1 个答案:

答案 0 :(得分:1)

你可以这样做:

demographic = Demographic.objects.get(id=7)
PersonDemographic.objects.bulk_create(
    [PersonDemographic(person=person, demographic=demographic) for person in Person.objects.some_query_set()]
)