Shin
Shin

Reputation: 684

Django: Limit the number of returned ManyToMany objects

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?

Upvotes: 0

Views: 154

Answers (1)

denvaar
denvaar

Reputation: 2214

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:]

Upvotes: 1

Related Questions