On Jul 23, 11:07 am, kostia <kostya.demc...@gmail.com> wrote:
> Hi everybody,
>
> I have 3 models:
>
> built-in User model,
>
> class Project(models.Model):
>    author = models.ForeignKey(User, verbos_name=_('Author'),
> related_name='projects')
>    title = models.charField(_('Title'), max_length=150)
>
> class Vote(models.Model):
>    project = models.ForeignKey(Project, verbos_name=_('Project'),
> related_name='votes')
>    user = models.ForeignKey(User, verbos_name=_('User'),
> related_name='votes')
>     date = models.DateTimeField(_('Date'),
> default=datetime.datetime.now)
>
> So users can be authors of the projects and they can vote for the
> projects.
>
> I have the view to show list of projects, when I want to order
> projects by votes.count
>
> As far as Project model does not contain the Votes field (it is
> realised as Many-To-Many table), I do not know how to write DB query
> like this:
>
> projects = Project.objects.order_by('votes')
>
> So I decided to take the projects as follows:
> projects = Project.object.all()
>
> And then foreach project count the votes number. But is is time-
> consuming. Also I do not know if this is true:
> for project in projects
>    project.votes = project.votes.count
>
> projects = sorted(projects, votes)
>
> Do you know any approach to do it on the fly? I mean the most efective
> way.

You need to use the aggregation features to count all the votes for a
given project, then order by that count. This should work:

    from django.db.models import Count
 
Project.objects.all().aggregate(votes_count=Count('vote')).order_by('votes_count')
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@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