[Fixed]-How to limit number of records in Django Rest Framework reverse relations

17👍

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]

Leave a comment