Skip to content

How to Add a New API Model Base on Alias Sample

Emerson Castaneda edited this page Mar 1, 2021 · 1 revision

HOWTO: Django Notes Adding Alias API/Model

1. Adding Model Alias under: civictechindexadmin/data/models.py

####### Alias ###########
class Alias(models.Model):
    tag = models.CharField(max_length=30)
    alias = models.CharField(max_length=30)

    def __str__(self):
        return f"Alias {self.id}: {self.tag} {self.alias}"

2. Making migrations

(base) ~/hackforla/CTI-website-backend$ docker-compose exec web python manage.py makemigrations

Generated files:

	civictechindexadmin/data/migrations/0009_alias.py
	civictechindexadmin/contrib/sites/migrations/0004_auto_20210205_2112.py
	civictechindexadmin/users/migrations/0002_auto_20210205_2112.py

Note 1: for this particular case makemigrations generated 3 files, because two of them are totally unrelated to the new Alias API/Model, those two additional files: 0004_auto_20210205_2112.py and 0002_auto_20210205_2112.py have been removed.

Note 2: Before running the migration, one should rename it to something descriptive. When adding a single table, the autogenerated name is usually good enough, for this particular case we got 0009_alias.py - but when the name is something like 0002_auto_20210205_2112, it needs to be renamed.

Content of civictechindexadmin/data/migrations/0009_alias.py:

# Generated by Django 3.1.5 on 2021-02-05 21:12

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('data', '0008_add_link_status_fields'),
    ]

    operations = [
        migrations.CreateModel(
            name='Alias',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('tag', models.CharField(max_length=30)),
                ('alias', models.CharField(max_length=30)),
            ],
        ),
    ]

3. Adding admin class AliasAdmin under civictechindexadmin/data/admin.py

3.1. Importing the model class

from .models import Organization, Link, FAQ, NotificationSubscription, Alias

3.2. Defining admin class AliasAdmin

class AliasAdmin(admin.ModelAdmin):
    model = Alias
    list_display = ('id', 'tag', 'alias')
    list_filter = ('tag', 'alias',)
    search_fields = ('tag', 'alias')

3.3. Registering admin class

admin.site.register(Alias, AliasAdmin)

4. Adding Serializer AliasSerializer under: civictechindexadmin/data/api/serializers.py

4.1. Importing the model class

from ..models import Organization, Link, FAQ, NotificationSubscription, Alias

4.2. Defining serializer class

class AliasSerializer(serializers.ModelSerializer):
    class Meta:
        model = Alias
        fields = ['id', 'tag', 'alias', ]
        depth = 1

5. Adding View AliasViewSet under: civictechindexadmin/data/api/views.py

5.1. Importing serializer class

from .serializers import OrganizationSerializer, LinkSerializer, FAQSerializer, NotificationSubscriptionSerializer, AliasSerializer

5.2. Importing the model class

from ..models import Organization, Link, FAQ, Alias

5.3. importing CreateModelMixin in order to make available POST method:

from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin, CreateModelMixin

5.4. Defining view class including CreateModelMixin

class AliasViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet, CreateModelMixin):
    serializer_class = AliasSerializer
    queryset = Alias.objects.all()
    lookup_field = "alias"

Note: In fact, for this , particular example, we want to write to the Alias table from the front end, and it is why we have incorporatedCreateModelMixin, for the opposite case, you should probably have just ReadOnlyModelViewset

For additional information about ReadOnlyModelViewset and ViewSets please visit the official documentation available here

6. Registering API router at config/api_router.py

6.1. Importing view:

from civictechindexadmin.data.api.views import (
    OrganizationViewSet, LinkViewSet, FAQViewSet, AliasViewSet,
    subscribe
)

6.2. registering router:

router.register("aliases", AliasViewSet)

7. Rebuilding container

(base) ~/hackforla/CTI-website-backend$ docker-compose up -d --build