Creating Models — Django

Build a Product Review Backend with DRF — Part 1

Emre Cevik
Python | Django & Rest
5 min readOct 12, 2020

--

We can create basic product information backend with django rest framework.

Setup django and django rest framework and markdown support for the browsable API.

$ pip install django
$ pip install djangorestframework
$ pip install markdown

From the command line, cd into a directory where you’d like to store your code, then run the following command:

$ django-admin startproject medium

To create your app, make sure you’re in the same directory as manage.py and type this command:

$ python manage.py startapp reviews

Database Setup :

By default, the configuration uses SQLite. SQLite is included in Python, so you won’t need to install anything. If you wish to use another database, install the appropriate database bindings, and change the “ENGINE” and “NAME” in the DATABASES ‘default’. We will use SQLite for this project.

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

Some built in applications make use of database table, though, so we need to create the tables in the database before we can use them.

$ python manage.py migrateOperations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial… OK
Applying auth.0001_initial… OK
Applying admin.0001_initial… OK
Applying admin.0002_logentry_remove_auto_add… OK
Applying admin.0003_logentry_add_action_flag_choices… OK
Applying contenttypes.0002_remove_content_type_name… OK
Applying auth.0002_alter_permission_name_max_length… OK
Applying auth.0003_alter_user_email_max_length… OK
Applying auth.0004_alter_user_username_opts… OK
Applying auth.0005_alter_user_last_login_null… OK
Applying auth.0006_require_contenttypes_0002… OK
Applying auth.0007_alter_validators_add_error_messages… OK
Applying auth.0008_alter_user_username_max_length… OK
Applying auth.0009_alter_user_last_name_max_length… OK
Applying auth.0010_alter_group_name_max_length… OK
Applying auth.0011_update_proxy_permissions… OK
Applying auth.0012_alter_user_first_name_max_length… OK
Applying sessions.0001_initial… OK

Now we’ll define our models with relations

A model is the single, definitive source of information about our data. It contains the essential fields and behaviors of the data we’re storing.

Models to be created: Category, Company, Product, ProductSite, ProductSize, Comment, User (built-in)

Let’s start by opening the models.py file, and start adding some models and fields.

- reviews/models.py

Let’s describe the Product Model

class Product(models.Model):
name = models.CharField(max_length=255)
content = models.TextField()
category = models.ManyToManyField(Category, related_name='products')
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.name

Each model is a Python class that subclasses django.db.models.Model. Django models come with many built-in model field types. Each field in your model should be an instance of the appropriate Field class. We’ve used four in this model. CharField is used for short strings and specifies a maximum length. TextField is similar to CharField but can be used for longer form text as it doesn’t have a maximum length limit. DateField can be used for store dates. Finally ManyToManyField can be used for specify a many-to-many relationship. In this model specify relationships between Product and Category models.

The Meta class inside the model contains metadata. We tell Django to sort results in the created field in descending order by default when we query the database. We specify descending order using the negative (-) prefix. Adding class Meta to a model is completely optional.

The __str__() method is the default human-readable representation of the object. Django will use it in many places, such as the administration site.

For more information please visit django documentation :

Many-to-one relationships : (models.ForeignKey)

product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='sites', related_query_name='site')

Many-to-many relationships : (models.ManyToManyField)

category = models.ManyToManyField(Category, related_name='products')

related_name will be the attribute of the related object that allows you to go ‘backwards’ to the model with the foreign key on it.

related_query_name is for use in Django querysets. It allows you to filter on the reverse relationship of a foreign key related field.

For example :

class Comment(models.Model):
...
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments', related_query_name='comment')
...

You can access the “Comment” instances that are related to your “Product“ instance by going product_instance.comments.all().

related_query_name enable you to use “comment” as a lookup parameter in a queryset, like: Product.objects.filter(comment=filter_what_you_want).

It isn’t necessary to specify both (or either of) related_name and related_query_name. Django has sensible defaults.

For more information please visit django documentation :

To include the app in our project, we need to add app or a reference to its configuration class in the INSTALLED_APP setting.

# Application definitionINSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'reviews'
]

OR

# Application definitionINSTALLED_APPS = [
'reviews.apps.ReviewsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Now Django knows to include the reviews app.

By running makemigrations you’re telling Django that you’ve made some changes to your models and that you’d like the changes to be stored as a migration.

$ python manage.py makemigrationsMigrations for 'reviews':
reviews\migrations\0001_initial.py
- Create model Category
- Create model Company
- Create model Product
- Create model ProductSize
- Create model ProductSite
- Create model Comment

The migrate command, synchronizing the changes you made to your models with the schema in the database.

$ python manage.py migrateOperations to perform:
Apply all migrations: admin, auth, contenttypes, reviews, sessions
Running migrations:
Applying reviews.0001_initial... OK

You can download part 1 files from

In the next part, we’ll create admin site.

If you want to learn more about Django, do check out the documentation, django rest framework website and make sure to check out part of this series.

--

--