Django Notes: To Create A New Project
Django Notes: To Create A New Project
Django Notes: To Create A New Project
In an app:
apps.py is for configurations
models.py is for models
views.py is for actions (request handlers)
urls.py we should define an array called urlpatterns. It’s an array of the form:
urlpatterns = [
path(‘url/path/’, action_function_ref),
path(‘url/path2/’, include(‘playgounds.urls’),
]
- To create a model you should create a new class in the app’s model.py. This new class must inherit
from django.db.models.Model. Example of a model class is:
- django creates an id field by default for each model. To prevent that create any other field and mark it
as primery_key=True.
- You need to declare the relations only in one side not on both sides and djando will declare the other
automatically. To prevent that you can mark the field with related_name=’+’.
class Collection(models.Model):
title = models.CharField(max_length=255)
class Promotion(models.Model):
title = models.CharField(max_length=255)
discount = models.FloatField()
class Product(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
class Customer(models.Model):
MEMBERSHIPS_LIST = [
('B', 'Bronze'),
('S', 'Silver'),
('G', 'Gold')
name = models.CharField(max_length=255)
email = models.EmailField(unique=True)
birth_date = models.DateField(null=True)
membership = models.CharField(max_length=1, choices=MEMBERSHIPS_LIST, default='B')
class Address(models.Model):
street = models.CharField(max_length=255)
- You can have some customization over the created DB for each model by creating Meta class inside
the class of the model
Example:
class Customer(models.Model):
MEMBERSHIPS_LIST = [
('B', 'Bronze'),
('S', 'Silver'),
('G', 'Gold')
]
name = models.CharField(max_length=255)
email = models.EmailField(unique=True)
birth_date = models.DateField(null=True)
membership = models.CharField(max_length=1, choices=MEMBERSHIPS_LIST, default='B')
class Meta:
indexes = [
models.Index(fields=['name']),
models.Index(fields=['membership']),
]
Migrations:
- To create a migration:
python manage.py makemigrations
- To run migrations:
pyhton manage.py migrate
- To go to a specified migrations:
pyhton manage.py migrate customer 003
Change DB settings:
- Go to settings.py and change the DATABASE settings
• Product.objects.filter(description__isnull=True)
For sorting:
• Product.objects.filter( price__lt=100.0).order_by(“title”, “-desciption”). This sort
by title ascending and description descending.
This will fetch also the collection table. Note that ‘collection’ is the name of a field in the Product
model.
Product.objects.prefetch_related(‘promotions’).all()
Aggregate functions:
result = Product.objects.aggregate(prod_count=Count(‘id’))
Note this will return a dictionary in the form:
{‘prod_count’: 1000}
ExpressionWrapper:
Used for casting the results of an expression into a new type.
Custom Manager:
class ProductManager(models.Manager):
def fn_that_do_complex_process(self, params):
pass
Then in the Product model class you need to add the following attribute:
class Product(models.Model):
objects = ProductManager()
……
first_product = query_set[0]
The last line will not generate a new SQL query, but will use the cashed data.
Creating Objects:
method 1:
product = Product()
product.collection = Collection(id=2)
product.save()
method 2:
product = Product.objects.create(title=‘good product’, description=‘Bla bla bla’,
collection_id=2)
Updating Objects:
method 1:
customer = Customer.objects.get(pk=1)
customer.last_name = 'Soso'
customer.save()
method 2:
Customer.objects.filter(id=1).update(last_name='Soso')
Note that method 2 is better performance wise because you don’t have to read the object first from the
DB then update it.
Deleting Objects:
method 1:
customer = Customer(pk=1)
customer.delete()
method 2:
Customer.objects.filter(id__gt=5).delete()
Transactions:
To run a multiple statements inside a DB transaction you can either annotate their method with:
@transaction.atomic()
Or wrap the code in a with block:
with transaction.atomic():
bla bla bla
Otherwise if our raw SQL query will not be mapped to only one model we can use the following
approach:
try:
cursor = connection.cursor()
cursor.execute(‘SOME COMPLEX QUERY’)
catch Exception:
pass
finally:
cursor.close()
Or instead of using try catch you can use with clause:
with connection.cursor() as cursor:
cursor.execute(‘SOME COMPLEX QUERY’)
You can also use this last method to call DB stored procedures:
with connection.cursor() as cursor:
cursor.callproc(‘my_sp’, [‘str_param1’, int_praram2])
Admin site
Note: the admin site depends on the Session App, so you need to add it to the installed app first
('django.contrib.sessions'), then run migrate.
To create new admin user:
python manage.py createsuperuser
Then you need to register the models you want to display in the admin page by adding the following
line to the app’s admin.py file:
admin.site.register(models.Collection)