0

我有一个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()
4

1 回答 1

2

你可以这样做:

demographic = Demographic.objects.get(id=7)
PersonDemographic.objects.bulk_create(
    [PersonDemographic(person=person, demographic=demographic) for person in Person.objects.some_query_set()]
)
于 2013-09-11T04:35:50.333 回答