create-model-and-api.mo

Prerequisites (~45 mins)

  • Have a django project installed with an app created

    see thisarrow-up-right.

  • In this example we will use an already existing model city in a locations app, to show how to integrate other

    models with foreign keys.

Steps

  • In this tutorial we will create a News model, add it to the Django admin back-office and create a GET API route to

    retrieve all the news that have been created.

Create a News model (~10 min)

  • In this example we will create a new model called News that has different attributes as you will see bellow. In the

    models.py file of your app (in our case Publications) create a new model.

# File: "our_django_project/publications/models.py"
from django.db import models

class News(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(max_length=1000)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    city = models.ForeignKey('locations.city')

    class Meta:
        verbose_name_plural = "News"

    def __str__(self):
        return self.title
  • CharField will return a single line form in the admin; max_length speaks for itself.

    Here is the Django doc for more informationarrow-up-right.

  • TextField will return a scrollable paragraph in the admin.

  • auto_now_add generates automatically a timestamp when a news is created.

  • auto_now updates the timestamp every time you change the news.

  • Concerning the city attribute which is a many to one relationship: every piece of news is linked to one city, two pieces of news can have the same city.

  • It's standard that the name of a model (not class) is singular, and django automatically puts it to plural for external use. However here, News is a singular/plural english name, so we need to make sure Django does not add a second 's' (Newss) by overriding verbose_name_plural

  • Finally, make your migrations and migrate. To do this run the following commands in your shell:

or adapt the previous commands, if you run your project with docker.

Note: Here is an article that goes into more detail How to Create Django Data Migrationsarrow-up-right

What you can check!

  • In the shell display the table (in case of psql \d) and check the existence of your model. More info herearrow-up-right

Add permissions to a group (~10 min)

  • Users that are in groups need permission to access the Model. If you don't have a group yet, you can create one by

    clicking on group on the admin web site. We can now add permissions to them that will be automatically added when

    you deploy.

  • You can than create a migration to add the groups permissions when the migrations are run

  • Create an empty migration:

  • Then fill in your migration like so:

  • Then run

What you can check!

Add the News model to the admin (~5 min)

  • We now need to add the model to the admin back-office.

If you don't add the list_display property, the default column title in the admin will be the result of the magic method str returned in the model (you can read more herearrow-up-right). list_display allows you to add several columns to the admin interface.

Without list_display:

With list_display:

What you can check!

Note: you can learn how to add other configuration to your admin by reading the official documentationarrow-up-right

Serialize the News you get from the database (~5 min)

  • Serializers translates Django models into other formats(json, xml). In our project want to get a JSON response. Check out the official Django docarrow-up-right for more info.

Create a News ViewSet (~5 min)

  • ViewSets will allow you to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically

Note: Check out the Django doc for more info ViewSetsarrow-up-right

  • The NewsViewSet class will now inherit both classes FilterByCity viewsets.ModelViewSet from right to left. Therefore, the FilterByCity get_queryset method will override the ModelViewSet one.

Note: You can also use automatically generated filters (have a look herearrow-up-right)

Mount the News ViewSet to an endpoint using a router (~5 min)

  • Django routers will allow you to easily generate different routes from your ViewSet (GET, POST, ...)

Note:Here is the Django docarrow-up-right if you want to learn more about Django routers

What you can check!

Last updated