Sunday, September 24, 2017

[Django] Models with django-mssql

 Python    Django    Django MSSQL 
  

(From Django MSSQL)




▌Introduction


We will integrate Django MSSQL and Django for creating tables and columns in Sql server by Django Models.


▌Environment


▋Python 3.6.2
▋Django 1.8.18



▌Implement


▋Install packages

From Django MSSQL document, we can see the dependencies.




▋Django downgrade (Optional)


Notice that the latest release only support Django 1.8.X
Use this command to install the latest version of 1.8.X

$ python -m pip install "Django~=1.8.0"


PS. The ~= syntax means that we are going to install the latest release on 1.8.X.


▋Django MSSQL

$ python -m pip install django-mssql



▋pypwin32

$ python -m pip install pypiwin32



Here is my pip list.





▋Models

The db schema will be looked like this.
[Products].[ProdTypeId] is a foreign key of [ProductTypes].




Open models.py in your app.



▋models.py

from django.db import models

class Product(models.Model):

    Id = models.IntegerField(primary_key=True)
    Price = models.IntegerField(null=False)
    Title = models.CharField(max_length=100, null=False)
    ProdTypeId = models.ForeignKey('ProductType', db_column='ProdTypeId', related_name='Products_ProductTypes')

    def __str__(self):
        return self.Title

    class Meta(object):
        db_table = "Products"

class ProductType(models.Model):

    Id = models.IntegerField(primary_key=True)
    Name = models.CharField(max_length=50, null=False)

    def __str__(self):
        return self.Name
 
    class Meta(object):
        db_table = "ProductTypes"



1.
   
class Meta(object):
        db_table = "Products"

db_table is an option for setting the table name of this model.

2.

ProdTypeId = models.ForeignKey('ProductType', db_column='ProdTypeId', related_name='Products_ProductTypes')

This line from model: Product, will create a foreign key to model: ProductType.


db_column:
Set the column name for this foreign key.

The name to use for the relation from the related object back to this one.



▋Database connection information

Go to settings.py, update the DATABASES configuration as following.


▋settings.py

DATABASES = {
    'default': {
        'ENGINE': 'sqlserver_ado',
        'HOST':'{Server name/IP}',
        'NAME': '{db name}',
        'USER':'{user}',
        'PASSWORD':'{pwd}',
        'PORT':'1433',
        'OPTIONS':{
            'provider':'SQLOLEDB'       
}
    },
}



▋Update installed app

Before we do the database migration, we have to update the installed app.

▋settings.py

# Application definition

INSTALLED_APPS = [
    'app', #PUT you app name here
    'django.contrib.admin',
$
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]



▋Database migration

First, create a migration.

$ python manage.py makemigrations {app}

Which {app} is your app name.



We can find the migration file in app/migrations



Let’s start migrating the database.

$ python manage.py migrate {app}





▋Check it up!

Lets see if the migration works.


▋Tables





▋Enabled migration history





▋Products and ProductTypes






▌Github





▌Reference





No comments:

Post a Comment