I have a model for articles which takes a field FileField which is supposed to be a markdown file for the user to load their article already. I expose the api with a ModelViewSet.
This is saved to my media folder. I could fetch the content from the client side by GETing it from the href of course but that would mean 2 requests to my server:
- get article info (title, content- this is the md, date published, description, etc.. ).
- get content from the link.
But i'm wondering if there's a way to tell django to just send the content of the file instead of the href when it responds to a requestion for the article item.
Here's my model and api:
# ---------------------- # # src/articles/models.py # # ---------------------- # from os.path import splitext from uuid import uuid4 from django.db import models # Create your models here. def hashFilename(instance, name): ext = splitext(name)[1] return "articles/{}{}".format(uuid4(), ext) def hashImageFilename(instance, name): ext = splitext(name)[1] return "images/{}{}".format(uuid4(), ext) class Article(models.Model): title = models.CharField(("title"), max_length=100) content = models.FileField("content", upload_to=hashFilename) description = models.TextField(("description"), default='') uploadDate = models.DateTimeField(("uploadDate"), auto_now=True) lastModified = models.DateTimeField(("uploadDate"), auto_now=True) publicationDate = models.DateField("publicationDate") image = models.ImageField("image", upload_to=hashImageFilename) def __str__(self): return self.title # ------------------------- # # src/articles/api/views.py # # ------------------------- # from rest_framework.viewsets import ModelViewSet from ..models import Article from .serializers import ArticleSerializerFull, ArticleSerializerShort class ArticlesViewSet(ModelViewSet): queryset = Article.objects.all() def get_serializer_class(self): if self.action == 'list': serializer = ArticleSerializerShort else: serializer = ArticleSerializerFull return serializer queryset = Article.objects.all()