Note that there are some explanatory texts on larger screens.

plurals
  1. POcorrectly aggregating model objects and simple view calculation
    text
    copied!<p>if "allotted_pto" (paid time off) is an integer field (expressing number of days) in a UserProfile model:</p> <pre><code>class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) fullname = models.CharField(max_length=64, unique=False) company = models.CharField(max_length=50, choices=CLIENT_CHOICES) ... allotted_pto = models.IntegerField(max_length=2, blank=True, null=True) ... User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) </code></pre> <p>and "total_days" returns an integer from a vacation request model:</p> <pre><code>class LeaveRequest(models.Model): employee = models.ForeignKey(UserProfile) supervisor = models.ForeignKey(UserProfile, related_name='+', blank=False, null=False) ... total_days = models.IntegerField(max_length=2, blank=True, null=True) def __unicode__ (self): return u'%s %s' % (self.employee, self.submit_date) def save(self, *args, **kwargs): fromdate = self.start_date todate = self.return_date daygenerator = (fromdate + timedelta(x + 1) for x in xrange((todate - fromdate).days)) self.total_days = sum(1 for day in daygenerator if day.weekday() &lt; 5) super(LeaveRequest, self).save(*args, **kwargs) ... </code></pre> <p>how can I construct a view that gives me the sum of "total_days" from a filter set of records and subtract that sum from the "allotted_pto" in the user profile? The simple view I wrote (see below) produces the number of "total_days" objects (in dictionary form) as opposed to counting the actual days, and the request for "allotted_pto" is apparently incorrectly constructed because it returns nothing at all...</p> <pre><code>#views.py def leave_screen(request, id): profile = UserProfile.objects.get(user=id) records = LeaveRequest.objects.filter(employee=id) agg_pto = LeaveRequest.objects.aggregate(Count('total_days')) if profile.allotted_pto: #if the allotted_pto field in UserProfile is not empty allotted_pto = profile.allotted_pto remaining_pto = allotted_pto - agg_pto else: remaining_pto = "na" return render_to_response("vacation/leave_request.html", {'records': records, 'agg_pto': agg_pto, 'remaining_pto': remaining_pto}) </code></pre> <hr> <p>ok, figured out calculation:</p> <pre><code>def leave_screen(request, id): ... agg_pto = LeaveRequest.objects.filter(employee=id).aggregate(Sum('total_days')) agg_pto = agg_pto['total_days__sum'] </code></pre> <p>just have to figure out how to pull the allotted_pto integer from the User Profile model.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload