對於ForeignKeys,我可以做select_related(),但是有什麼辦法可以做類似於BooleanFields的事嗎?如果一個對象的is_app_category設置爲True,那麼我的應用程序目前正在檢查600次以上,這是一種矯枉過正的行爲,並且需要10秒鐘才能加載頁面(仍然是一個小數字,因爲最終產品將有數千個條目)。的.py:django - 在一個查詢集中獲得所有具有True值的對象
def assign_app_categories(request):
user = request.user
if user.is_admin:
category_list = Categories.objects.select_related('company').filter(show_in_menu = True, is_app_category = False)
else:
category_list = Categories.objects.filter(company = user.company, show_in_menu = True)
number_of_categories = len(category_list)
zipped_data = {}
CategoriesFormSet = formset_factory(CategoriesAssignForm, extra = number_of_categories)
if request.method == "POST":
categoriesFormSet = CategoriesFormSet(request.POST)
if categoriesFormSet.is_valid():
for (name, cleaned_form) in zip(category_list, categoriesFormSet.cleaned_data):
if cleaned_form.get('parent') != None:
if user.is_admin:
category_item = Categories.objects.filter(name = name).filter(show_in_menu = True)[0]
else:
category_item = Categories.objects.get(company = user.company, name = name)
category_item.parent = cleaned_form.get('parent')
category_item.show_in_menu = False
category_item.save()
messages.success(request, _('Categories are assigned to App categories!'))
history = HistoryLog(user = request.user, function = 'categories.assign_app_categories', kind = 404).save()
return HttpResponseRedirect('/categories/')
else:
categoriesFormSet = CategoriesFormSet()
zipped_data = zip(category_list, categoriesFormSet)
return render(request, 'categories/assign.html', {'zipped_data': zipped_data, 'category_list': category_list, 'categoriesFormSet': categoriesFormSet, 'menu':'categories'})
的Django調試工具欄:
SELECT "categories_categories"."id",
"categories_categories"."is_app_category",
"categories_categories"."brand_id",
"categories_categories"."company_id",
"categories_categories"."name",
"categories_categories"."slug",
"categories_categories"."description",
"categories_categories"."show_in_menu",
"categories_categories"."gender",
"categories_categories"."parent_id",
"categories_categories"."products_count",
"categories_categories"."date_create",
"categories_categories"."date_modified"
FROM "categories_categories" WHERE "categories_categories"."is_app_category" = 'True'
Duplicated 633 times.
你真的需要'Q'查詢嗎?不會'過濾(show_in_menu = True,is_app_category = False)'做同樣的事情? – Sayse
是的。這個項目已經交給了我一個不在這裏工作的人,我的工作是解決它並使其運行平穩。由於大多數事情並不像預期的那樣工作,所以很難做。 – jarkow
雖然我的建議能解決問題嗎?它可能會使查詢稍微快一點,但對於任何性能增強......您在類別中實際需要哪些值?它如何被使用? – Sayse