Kes*_*iya 7 django django-queryset
class Parent(models.Model):
# some fields
class Child(models.Model):
parent = models.ForeginKey(Parent)
species = models.ForeignKey(Species)
# other fields
Run Code Online (Sandbox Code Playgroud)
我有一个这样的函数:
1. def some_function(unique_id):
2. parent_object = Parent.objects.get(unique_id=unique_id)
3. new_child = Child.objects.create(name='Joe', parent=parent_object)
4. call_some_func(new_child.parent.name, new_child.species.name)
Run Code Online (Sandbox Code Playgroud)
在第 4 行中,为 生成了一个数据库查询Species。有什么办法,我可以使用 select_lated 来预取Species,以防止额外的查询。
可以在我使用的时候完成吗.create()?这只是一个例子,我也使用许多其他字段,它们每次都查询数据库。
我能想到的唯一方法是在第 3 行之后使用以下代码:
child_obj = Child.objects.select_related('species').get(id=new_child.id)
Run Code Online (Sandbox Code Playgroud)
唯一create接受的参数force_insert与您所要求的内容无关,因此看来这是不可能的。另外,注意到create执行INSERT ... RETURNING ...语句,我认为无论如何这是不可能的,因为您无法从其他表返回列。
最好的方法可能是您已经建议的:get()事后对您需要的相关字段进行操作。
| 归档时间: |
|
| 查看次数: |
501 次 |
| 最近记录: |