Django CRUD - ORM and mySQL

김하성·2021년 1월 25일
0
post-thumbnail

Object-related Mapping (ORM): converting data between incompatible type systems using object-oriented programming language. Django serves as the object-related mapper and converts data objects (classes in models.py) to data used in databases (mySQL). Whenever you makemigrations, Django stores the various changes you made to models.py in the migrations folder. You can edit and view these python files directly to see the exact changes that are to be applied to your database. Once you hit python manage.py migrate, these changes are effectively applied to the database. You can also use python manage.py showmigrations to view which migrations have been applied and which have still yet to be applied.

Projects vs Apps

An app is a web application that has a specific function, such as a blog system, a database of public records, or a small polling app. A project is a collection of configuration and apps for a particular website. A project can contain many apps, and each app can be used for different projects

Things to Remember:

  • ALWAYS REMEMBER TO INCLUDE indented class Meta: (db_table='menu')
  • Each class in models.py is one table
  • Each attribute in a class in models.py is a table column (migrate each time you add something to a class)
  • For many-to-many tables, use the models.ManyToManyField() and insert parent table into the parentheses

MySQL

MySQL keys
mysql> show databases;
mysql> use westarbucks
mysql> show tables;
mysql> SELECT * FROM tablename;
mysql> DESC products;

Using python manage.py shell for CRUD

python manage.py shell
from products.models import "Classes"

CREATE

Product.ojects.create(name="pen", description="this is a pen.", price="32")
p1 = Product.objects.create()
product.save() *** when creating an object through a variable (p1 = Product.objects.create()), make sure to use .save() to save the creation (otherwise creation will not be recorded in database)

READ

Product.objects.all() --> .all
Product.objects.all() --> products안에 있는 모든 겍체를 가지고 오는 method
product = Products.objects.get(id=1) --> .get brings only one object and saves to a variable --> can update and read variable according to class attrib utes
Products.objects.filter(age=33) --> .filter gets all objects that match the specified requirement
Product.objects.values() --> .values() returns each category object in a list of dictionaries (each category object is one dictionary)
Product.objects.values_list() --> .values_list() returns each category object in a list of tuples

UPDATE

product = Products.objects.get(id=1)
product.name = 'Americano'
product.korean_name = '아메리카노'
Drink.objects.filter(drink_id=1).update(name='everyone is now an Americano")

DELETE

p1 = Products.objects.get(id=1)
p1.delete() --> deletes category object from database

profile
#mambamentality 🐍

1개의 댓글

comment-user-thumbnail
2021년 1월 25일

잘 보고 갑니다~

답글 달기