JREAM
JREAM

Reputation: 5931

Django Model Latest Foreign Key Record

From a Django Model, how do I get a complete list of all these snippets a including only the latest revision foreign-key?

There could be a snippet with 5 revisions, but I only want the newest one to show.

# models.py
class Revision(models.Model):
    slug = models.CharField(max_length=16)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Snippet(models.Model):
    user = models.ForeignKey(User)
    revision = models.ForeignKey(Revision)

# views.py
def a_view(request):
    Snippets.objects.all().filter(user=request.user)

I can't see a way to say .filter(revision__max=id). I actually don't know what to do because I think I might be laying out the model wrong when I think it out.

Upvotes: 1

Views: 505

Answers (1)

alecxe
alecxe

Reputation: 473833

You can use latest():

Snippets.objects.filter(user=request.user).latest('revision__created_at')

Upvotes: 4

Related Questions