0

I am using django.core.serializers to serialise my Queryset and then return it as JSON later on.

from django.core import serializers
from .models import MyModel

def a_view(request):
    objects = MyModel.objects.all()
    serializers.serialize('json', objects, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True)

Let's say MyModel has MyModel.data, which is a ManyToManyField that could have thousands of relations. I would like to only get the latest X objects of MyModel.data in this case.

How would I do this?

Shin
  • 678
  • 3
  • 12
  • 22

1 Answers1

1

You could get all of the objects and use [:] to chop off what you don't want. Is that what you mean?

MyModel.data.order_by('-id')[5:]
denvaar
  • 2,174
  • 2
  • 22
  • 26