A.J.
A.J.

Reputation: 9015

How to limit number of records in Django Rest Framework reverse relations

I am getting started with Django Rest Framework, and it's behaving quite well. I got all the stuff working as I wanted it to be. I have came across a problem that I am not getting answer of.

I am using reverse relationship.

Models

class Province(models.Model):
    name = models.CharField(max_length=50)
    intro = models.CharField(max_length=1000, null=True, blank=True)
    description = models.TextField(max_length=10000, null=True, blank=True)

class Picture(models.Model):
    name = models.TextField("Title", max_length=10000, null=True, blank=True)
    pro = models.ForeignKey(Province, verbose_name="Province")

When I write the reverse relationship serializers of Province, e.g. for a single province.

Views

ProToPicturesSerial(node, many=False).data

I get all the pictures in this province. I want to get some number of pictures, maybe last 3, or the 5 pictures that are added lately.

How can I limit the number of picture instance? Because as the number grows in the picture records, the application will tend to get slower.

Serializer

class ProToPicturesSerial(serializers.ModelSerializer):
    pro_pictures = PictureSerializer(many=True)

    class Meta:
        model = Province
        fields = ('id', 'name', 'intro', 'description', 'pro_pictures')

Let me know if I am missing something obvious.

Upvotes: 16

Views: 3754

Answers (1)

almalki
almalki

Reputation: 4775

You can point the source attribute of PictureSerializer to a method on province that returns only 3 related pics:

class ProToPicturesSerial(serializers.ModelSerializer):
    pro_pictures = PictureSerializer(many=True, source='first_three_pics')

    class Meta:
        model = Province
        fields = ('id', 'name', 'intro', 'description', 'pro_pictures')

and

class Province(models.Model):
    name = models.CharField(max_length=50)
    intro = models.CharField(max_length=1000, null=True, blank=True)
    description = models.TextField(max_length=10000, null=True, blank=True)

    def first_three_pics(self):
        return self.picture_set.all()[:3]

Upvotes: 17

Related Questions