我正在回到FormSet。 Django调试工具栏向我展示了对于is_valid()和save(),查询集中的每个模型都被重新查询,即使它们在构造FormSet期间已经从数据库中检索到了所有模型。这里没有特殊的对象关联。
E.g。用户有5个域。这将发出1 + 5 + 5个查询== 11个查询。如何消除最后10个查询?
版本:
models.py
class Domain(Model):
name = models.CharField(unique=True, max_length=255)
user = models.ForeignKey(User)
class Meta:
db_table = 'domain'
forms.py
class DomainForm(ModelForm):
class Meta:
model = Domain
DomainFormSet = modelformset_factory(Domain, form=DomainForm, extra=0)
class DomainFormSetWithQuerySet(DomainFormSet):
def __init__(self, user, data=None):
super(DomainFormSetWithQuerySet, self).__init__(data, prefix='domains', queryset=Domain.objects.filter(user=user))
views.py
def view(request):
if request.method == 'POST':
domain_formset = DomainFormSetWithQuerySet(request.user, request.POST)
// One big select query:
// select * from domains where user_id = ? order by id asc
//
// Then, an additional select query for each form in the formset:
// select * from domains where domain_id = ?
if domain_formset.is_valid():
// An additional select query for each form in the formset:
// select * from domains where domain_id = ?
domain_formset.save()