How can I eagerly load an answers latest revision?
I have a Q&A site and it allows answers to be changed while storing a revision of each change, much like here on Stackoverflow. When selecting some answers, I'd like it to include the most recent(but not all) revision as a property of each answer, so that I can avoid doing n+1 queries on my page.
class Answer(开发者_StackOverflow社区models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
class AnswerRevision(models.Model):
answer = models.ForeignKey(Answer, related_name='revisions')
text = models.TextField()
timestamp = models.DateTimeField()
Answer.objects.filter(problem=p)
I'd suggest the following structure:
class Answer(models.Model):
user = models.ForeignKey(User)
revision = models.ForeignKey(AnswerRevision)
problem = models.ForeignKey(Problem)
class AnswerRevision(models.Model):
answer = models.ForeignKey(Answer, related_name='revisions')
text = models.TextField()
timestamp = models.DateTimeField()
The only difference is that I added a revision
property to the answer. When a new revision is made, just change the FK to point to the new revision.
精彩评论