对于ForeignKeys我可以做select_related(),但是有什么方法可以做类似于BooleanFields的事情吗?我的应用程序当前检查超过600次,如果一个对象的is_app_category设置为True,这是一个过度的,加载页面需要10秒以上(仍然是一个很小的数字,因为最终产品将有数千个条目)
views.py:
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.
答案 0 :(得分:0)
虽然我无法肯定地说下面这些会有所帮助,但他们肯定不会受伤
.count()
user.is_admin
如果对我来说似乎很奇怪,因为您只是根据之前找到的类别重新过滤类别,并且因为检查name
只会进行pk比较,您和#39;不会过滤任何额外的内容,因此在进行任何此类过滤之前category_item
已经相当于name
。category_item
,您实际上并不关心,因此您可以在查询集上使用.update()
来更新数据库端的匹配结果< / LI>
醇>
除此之外,您需要查看category_list中实际需要的内容,您应该尝试使用values
或values_list
来仅返回您关注的字段。