Using Database models in Python and Django

If you are insterested in view how it looks the migration code in plain SQL, you can use the sqlmigrate command:python manage.py sqlmigrate example 0001It will show a list of SQL commands:BEGIN;—- Create model Message–CREATE TABLE "example_message" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "sender" varchar(200) NOT NULL, "recipient" varchar(200) NOT NULL, "message" varchar(200) NOT NULL, "visible" integer NOT NULL, "timestamp" datetime NOT NULL);—- Create model Sender–CREATE TABLE "example_sender" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(200) NOT NULL, "email" varchar(200) NOT NULL, "imageUrl" varchar(250) NOT NULL);COMMIT;Note: This output could vary between different versions of the SQLite database.Using Django Database OperationsInstead of running specific and complicated SQL commands, you can play with the Database functions provided by Django and Python..You can start a special python console ready to work with your application and models:python manage.py shellNow you have a console to execute python commands..Some useful commands to execute:from example.models import Sender, Message from django.utils import timezoneThe first line imports the objects Sender and Message associated to the tables created in the migration..The second one imports the timezone object to deal with date/time operations.Creating modelssender = Sender(email="me@example.com", name="Me Myself", imageUrl = "http://my/image.png")sender.save()sender.idThese lines created a new Sender object, filling their values..Then call save() to store this item in the database..After all, the sender will have a new ID (sender.id) assigned by the database.Updating modelssender.name = "Real Name"sender.save()Now, these lines updated theSender object, replacing some values..Calling save() will update this row in the database.Retrieving and Displaying models>>> Sender.objects.all()<QuerySet [<Sender: Real Name [me@example.com]>]>Calling {ModelName}.objects.all() will retrieve a full list of objects stored in the database for this model..This last command will return a simple description for each object..Each model object must implement the _str_(self) method to help python to show this information in an human-readable way.Filtering models# Filter exact match Sender.objects.filter(id=1)# Filter start textSender.objects.filter(email__startswith='me@')# Filter date parts (year)Message.objects.filter(timestamp__year=2018)# Filter a related field in an foreign tableMessage.objects.filter(sender__email="me@example.com") # Get an unique object using the primary key valueSender.objects.get(pk=1)Using objects.filter(params) you can do different types of filters:field=value : Simple filter, field equals to a valuefield__startswith=txt : Filter for text starting with a specific text..(Note the double _ _ to separate field and filter)datefield__year=value : Filter by a part of the date (year, month)The objects.get(params) method is to retrieve an unique item using the filter.Deleting modelssender = Sender.objects.get(pk=1)sender.delete()Using delete() in an model object will delete this item from the database.Include models in the admin moduleYou can easily create an administration page for your models using the django.contrib.admin component..Edit the admin.py file in the application folder (example/admin.py):from django.contrib import adminfrom .models import Senderfrom .models import Messageadmin.site.register(Sender)admin.site.register(Message)Now, when you run your server (python manage.py runserver), you will get additional options in your admin interface:Upgrading your modelsMany times you need to modify or redefine your models adding new fields, and adding or modifying relationships..In this case, we want to upgrade the Message model to make the sender and recipient attributes to use a relationship (Foreign key) with the Sender model.. More details

Leave a Reply