我有两个模型,它们之间有OneToOne关系。我想一次为他们中的每一个创建一个实例,以避免对服务器的两次查询(这有点慢)
class FilePath(models.Model):
storage_path = models.CharField(max_length=100)
date_created = ...
class Image(models.Model):
path = models.OneToOneField(FilePath, on_delete=models.CASCADE)
width = models.IntegerField()
# I want these queries to be combined to a single server access
file_path = FilePath.objects.create(storage_path=r"/images/1234.jpg")
image = Image.objects.create(path=file_path, width=250)
发布于 2019-02-05 21:54:20
Django中的bulk_create
函数就是您要找的。此函数以数组为参数,该数组包含要保存的对象。
示例:
Image.objects.bulk_create([
Image(path=gile_path, width=250),
Image(path=gile_path, width=250),
Image(path=gile_path, width=250),
])
有关更多信息,请阅读有关此函数的Django文档。bulk_create()。
https://stackoverflow.com/questions/54543237
复制