I have the field ‘submission’ which has a user and a problem. How can I get an SQL search result which will give a list of only one result per user-problem pair?
Models are like this:
class Problem(models.Model):
title = models.CharField('Title', max_length = 100)
question = models.TextField('Question')
class Submission(models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
solution = models.CharKey()
time = models.DateTimeField('Time', auto_now_add=True)
Update 2:
(After reading OP’s comments) I suggest adding a new model to track the latest submission. Call it
LatestSubmission.You can then either
Submission.save()to create/update the entry inLatestSubmissionevery time an user posts a new solution for a Problemsuch that
LatestSubmissionwill contain one row per problem-user-submission combination pointing to the latest submission for the problem by each user. Once you have this in place you can fire a single query:Update:
Since the OP has posted sample code, the solution can now be changed as follows:
Original Answer
In the absence of any date/time based criteria for deciding which is “older” or “newer”, you can use the primary key (
id) ofSubmissionto “neglect the old ones”.