我有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()
答案 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()]
)