Add custom Manager for Account model.

- When Account model is queried with Account.objects, it always add
  .select_related('cofprofile_user', 'negative').
- Eg benefits: history doesn't do anymore one request by account to
  fill the account filter.

Important

Using this workaround (systemically append select_related) can be
dangerous normally, however a certain number of properties in
cofprofile and user are frequently used (as firstname or lastname), and
the benefits seems greater.
This commit is contained in:
Aurélien Delobelle 2017-04-06 18:23:27 +02:00
parent 33cee05884
commit 709d421b2c
3 changed files with 30 additions and 18 deletions

View file

@ -46,6 +46,10 @@ class GenericTeamBackend(object):
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
return (
User.objects
.select_related('profile__acount_kfet')
.get(pk=user_id)
)
except User.DoesNotExist:
return None

View file

@ -27,8 +27,19 @@ def default_promo():
now = date.today()
return now.month <= 8 and now.year-1 or now.year
@python_2_unicode_compatible
class AccountManager(models.Manager):
"""Manager for Account Model."""
def get_queryset(self):
"""Always append related data to this Account."""
return super().get_queryset().select_related('cofprofile__user',
'negative')
class Account(models.Model):
objects = AccountManager()
cofprofile = models.OneToOneField(
CofProfile, on_delete = models.PROTECT,
related_name = "account_kfet")

View file

@ -346,35 +346,32 @@ def account_create_ajax(request, username=None, login_clipper=None,
'user_form' : forms['user_form'],
})
# Account - Read
@login_required
def account_read(request, trigramme):
try:
account = (
Account.objects
.select_related('cofprofile__user', 'negative')
.get(trigramme=trigramme)
)
except Account.DoesNotExist:
raise Http404
account = get_object_or_404(Account, trigramme=trigramme)
# Checking permissions
if not request.user.has_perm('kfet.is_team') \
and request.user != account.user:
raise PermissionDenied
addcosts = (OperationGroup.objects
.filter(opes__addcost_for=account,opes__canceled_at=None)
.extra({'date':"date(at)"})
.values('date')
.annotate(sum_addcosts=Sum('opes__addcost_amount'))
.order_by('-date'))
addcosts = (
OperationGroup.objects
.filter(opes__addcost_for=account,
opes__canceled_at=None)
.extra({'date': "date(at)"})
.values('date')
.annotate(sum_addcosts=Sum('opes__addcost_amount'))
.order_by('-date')
)
return render(request, "kfet/account_read.html", {
'account' : account,
'account': account,
'addcosts': addcosts,
'settings': { 'subvention_cof': Settings.SUBVENTION_COF() },
'settings': {'subvention_cof': Settings.SUBVENTION_COF()},
})
# Account - Update