First, I think that you're going about last_visit in the wrong way.
timezone.now() is evaluated once, when the module is imported,
rather than when the user visits.  DateTimeField's auto_now=True
option is tailor made for this kind of situation.

Next, since you have the user id, I'm going to assume that you have
an actual user object.  In the code below I'll presume that it's
request.user .

    visits_qs = Visit.objects.filter(user=request.user)
    total_visits_count = visits_qs.count()
    latest_visit = visits_qs.order_by('-last_visit')[0]

Yes, this is two database queries, but unless you are seeing a performance
issue that you've traced to the fact that this is more than one query, this
code is a heck of a lot more maintainable than trying to make it happen
in one.

Bill

On Tue, Jul 3, 2012 at 6:51 AM, J. Javier Maestro <jjmaes...@ieee.org> wrote:
> Hi there!
>
> I have the following model:
>
>   class Visit(models.Model):
>       user = models.ForeignKey(User)
>       visitor = models.ForeignKey(User, related_name="visitor")
>       last_visit = models.DateTimeField(default=timezone.now())
>       count_visits = models.IntegerField(default=0)
>
> I would like to make the following SQL query using the Django ORM:
>
>   SELECT last_visit, SUM(count_visits) AS total_count_visits
>   FROM core_visit
>   WHERE user_id=42
>   GROUP BY user_id
>   ORDER BY last_visit DESC
>
> So far, I haven't been able to do it. When I use values('user') and
> order_by('-last_visit') the last_visit column is automatically added
> to the GROUP BY clause. I've read in the Django doc that this is how
> it's supposed to be but I can't seem to understand it. Why do I have
> to group the results by whatever I choose as order? What am I missing?
>
> Also, I know I can do a RawQuerySet but unfortunately, I would like to
> be able to use a full QuerySet (this query goes into Tastypie and so
> far, I haven't been successful in using it with anything but full
> QuerySets, not even ValueQuerySets...)
>
> All help and ideas would be greatly appreciated.
>
> Thanks a lot in advanced,
>
> --
> J. Javier Maestro <jjmaes...@ieee.org>
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-users@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to