Django query to retrieve rows that match aggregate criteria in the corresponding table
I am really stuck on a Django request and hope you have a couple of minutes to help me figure it out.
I have a very simple model:
class Task(models.Model):
# a tuple representing a specific item to be searched for a specific URL
instructions = models.TextField()
ASSIGNMENT_STATUS_CHOICES = (
( 'a', 'assigned' ),
( 'c', 'submitted for review' ),
( 'f', 'finished' ),
( 'r', 'rejected' ),
)
class Assignment(models.Model):
# the overall container representing a collection of terms for a page found
# by a user
user = models.ForeignKey(User)
task = models.ForeignKey(Task, related_name='assignments')
status = models.CharField(max_length=1, choices=ASSIGNMENT_STATUS_CHOICES, default='a')
What I want to do is randomly select a task that has less than N assignments, which are the status! = 'R'. In other words, I want to make sure each task completes successfully N times, so if a worker requests a job, she needs one that has fewer than N tasks in a state that could lead to completion.
I was just completely lost trying to find a query that would return tasks like this. For this task, I can check:
task.assignments.exclude(status='r').count() < N
and if so, then this is the candidate. But how can I query Task.objects in such a way that it returns all candidates in one database query so that I can randomly select one of them:
Task.objects.<some magic filter>.order_by('?')[0]
Any help would be appreciated!
source to share