|
| 1 | +--- |
| 2 | +title : Object-Relational Mapping and RAW Selects in Django - Intro for Beginners |
| 3 | +sidebar_label : ORM & Raw Selects |
| 4 | +--- |
| 5 | + |
| 6 | +# Object-Relational Mapping |
| 7 | + |
| 8 | +<SubHeading>Learn more about Object-Relational Mapping and RAW Selects in Django (Intro for Beginners).</SubHeading> |
| 9 | + |
| 10 | +[Django's Object-Relational Mapping](https://docs.djangoproject.com/en/4.2/topics/db/queries/) (`ORM`) is a powerful tool that allows you to interact with your database using Python code, |
| 11 | +without writing SQL queries directly. |
| 12 | + |
| 13 | +It abstracts the database and provides a high-level, Pythonic way of managing and querying data. |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +> Here's a **comprehensive introduction to Django ORM**, along with samples and a brief introduction to raw **SQL selects**. |
| 18 | +
|
| 19 | +## ✅ **Setting up Models** |
| 20 | + |
| 21 | +In Django, models represent your application's data structure. They are defined in Python and automatically generate the database schema. Here's an example of defining a simple model: |
| 22 | + |
| 23 | +```python |
| 24 | +from django.db import models |
| 25 | + |
| 26 | +class Author(models.Model): |
| 27 | + name = models.CharField(max_length=100) |
| 28 | + |
| 29 | +class Book(models.Model): |
| 30 | + title = models.CharField(max_length=100) |
| 31 | + author = models.ForeignKey(Author, on_delete=models.CASCADE) |
| 32 | + publication_date = models.DateField() |
| 33 | +``` |
| 34 | + |
| 35 | +## ✅ **Creating Tables** |
| 36 | + |
| 37 | +After defining your models, you need to create database tables. Run the following command: |
| 38 | + |
| 39 | +```bash |
| 40 | +python manage.py makemigrations |
| 41 | +python manage.py migrate |
| 42 | +``` |
| 43 | + |
| 44 | +This will create the necessary tables in your database. |
| 45 | + |
| 46 | +## ✅ **Querying with Django ORM** |
| 47 | + |
| 48 | +Django ORM provides a rich API for querying the database. Here are some common queries: |
| 49 | + |
| 50 | +> **Filtering** |
| 51 | +
|
| 52 | +```python |
| 53 | +# Retrieve all books with 'Django' in the title |
| 54 | +books = Book.objects.filter(title__icontains='Django') |
| 55 | +``` |
| 56 | + |
| 57 | +> **Joins** |
| 58 | +
|
| 59 | +```python |
| 60 | +# Retrieve books with their author's name |
| 61 | +books_with_author = Book.objects.select_related('author') |
| 62 | +``` |
| 63 | + |
| 64 | +> **Aggregation** |
| 65 | +
|
| 66 | +```python |
| 67 | +from django.db.models import Count |
| 68 | +# Count the number of books by each author |
| 69 | +author_book_count = Author.objects.annotate(num_books=Count('book')) |
| 70 | +``` |
| 71 | + |
| 72 | +> **Sorting** |
| 73 | +
|
| 74 | +```python |
| 75 | +# Sort books by publication date in descending order |
| 76 | +books = Book.objects.order_by('-publication_date') |
| 77 | +``` |
| 78 | + |
| 79 | +> **Inserting Data** |
| 80 | +
|
| 81 | +```python |
| 82 | +new_author = Author.objects.create(name='J.K. Rowling') |
| 83 | +new_book = Book.objects.create(title='Harry Potter', author=new_author, publication_date='1997-06-26') |
| 84 | +``` |
| 85 | + |
| 86 | +> **Updating Data** |
| 87 | +
|
| 88 | +```python |
| 89 | +book = Book.objects.get(title='Harry Potter') |
| 90 | +book.title = 'Harry Potter and the Philosopher\'s Stone' |
| 91 | +book.save() |
| 92 | +``` |
| 93 | + |
| 94 | +> **Deleting Data** |
| 95 | +
|
| 96 | +```python |
| 97 | +book = Book.objects.get(title='Harry Potter') |
| 98 | +book.delete() |
| 99 | +``` |
| 100 | + |
| 101 | +## ✅ **Using Raw SQL Queries** |
| 102 | + |
| 103 | +While Django ORM is excellent for most tasks, there may be cases where you need to execute raw SQL queries. You can use the `connection` object for this purpose. For example: |
| 104 | + |
| 105 | +```python |
| 106 | +from django.db import connection |
| 107 | + |
| 108 | +def custom_sql_query(): |
| 109 | + with connection.cursor() as cursor: |
| 110 | + cursor.execute("SELECT * FROM myapp_book WHERE title = %s", ['Harry Potter']) |
| 111 | + results = cursor.fetchall() |
| 112 | + return results |
| 113 | +``` |
| 114 | + |
| 115 | +Remember to use raw SQL sparingly, as it bypasses Django's security features and may make your code less portable. |
| 116 | + |
| 117 | +## ✅ In Summary |
| 118 | + |
| 119 | +These are the basics of Django ORM and using raw SQL queries in Django. It's a powerful tool that can make database interactions in your web application more manageable and Pythonic. |
| 120 | + |
| 121 | +## ✅ Resources |
| 122 | + |
| 123 | +- 👉 Access [AppSeed](https://appseed.us/) for more starters and support |
| 124 | +- 👉 [Deploy Projects on Aws, Azure and DO](https://www.docs.deploypro.dev/) via **DeployPRO** |
| 125 | +- 👉 Create landing pages with [Simpllo, an open-source site builder](https://www.simpllo.com/) |
| 126 | +- 👉 Build apps with [Django App Generator](https://app-generator.dev/django/) (free service) |
0 commit comments