Friday, July 23, 2010

Django order_by ManyToMany Field

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 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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment