Skip to content

Creating a new app

Riccardo Campisano edited this page Aug 7, 2017 · 16 revisions

New apps

  • Run the follow command to create the new app, here called your_app_name:
cd ~/dri
source env/bin/activate
cd api
python manage.py startapp your_app_name
  • Add the app your_app_name in the var list PROJECT_APPS inside ~/dri/api/dri/settings/defaults.py

Naming convention

New Model

  • Create the new model, here called YourModel, inside ~/dri/api/your_app_name/models.py:
from django.db import models


class YourModel(models.Model):

    ymd_name = models.CharField(
        max_length=128,
        verbose_name='Internal Name',
        help_text='This is the internal name for the model.')
    ymd_display_name = models.CharField(
        max_length=128,     # if optional: null=True, blank=True, default=None
        verbose_name='Display Name',
        help_text='This is the model name to be displayed to the user.')

    def __str__(self):
        return self.ymd_display_name

  • Register the new model adding the information in the file inside ~/dri/api/your_app_name/admin.py, like the follow:
from django.contrib import admin
from .models import YourModel


class ImageAdmin(admin.ModelAdmin):
    list_display = ['id', 'ymd_name', 'ymd_display_name']
    search_fields = ['id', 'ymd_name', 'ymd_display_name']

admin.site.register(YourModel, YourModelAdmin)

New Serializer

  • Create the new serializer inside ~/dri/api/your_app_name/serializers.py:
from rest_framework import serializers
from .models import YourModel


class YourModelSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = YourModel
        fields = ['id', 'ymd_name', 'ymd_display_name']

New View

  • Create the new view inside ~/dri/api/your_app_name/views.py:

NOTE: you can use the simple way to obtain a default view with standard filter functionalities

from rest_framework import viewsets
from .models import YourModel
from .serializers import YourModelSerializer


class YourModelFilter(viewsets.ModelViewSet):
    """
    API endpoint that allows YourModel to be viewed or edited
    """

    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer
    filter_fields = ['id', 'ymd_name', 'ymd_display_name']

OR: you can define a custom Filter class to allow specific filter results

http://www.django-rest-framework.org/api-guide/filtering/#setting-filter-backends

https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html#adding-a-filterset-with-filter-class

https://django-filter.readthedocs.io/en/latest/ref/filterset.html#meta-options

import django_filters
from django.db.models import Q
from rest_framework import viewsets
from rest_framework import filters
from .models import YourModel
from .serializers import YourModelSerializer


class YourModelFilter(django_filters.FilterSet):
    group_by_name = django_filters.MethodFilter(action='filter_group_by_name')

    class Meta:
        model = YourModel
        fields = ['id', 'ymd_name', 'ymd_display_name']

    def filter_group_by_name(self, queryset, value):

        name = value

        q = queryset.filter(
            Q(ymd_name=value) | Q(ymd_display_name=value)
        )

        return q


class YourModelViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows YourModel to be viewed or edited
    """

    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = YourModelFilter

  • Add the follows line to the ~/dri/api/dri/urls.py:
from your_app_name import views as your_app_name_views
# ...
router.register(r'<yourmodel>', your_app_name_views.YourModelViewSet)

Migrate the model

python manage.py makemigrations your_app_name
python manage.py migrate your_app_name

Run the server and test

python manage.py runserver
firefox http://localhost:8000/