Created
March 25, 2026 12:36
-
-
Save sunmeat/b9f3beb78cb80b720c2c1806bab7fa77 to your computer and use it in GitHub Desktop.
Django Shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| python manage.py shell | |
| from django.apps import apps | |
| apps.get_models() | |
| from app.models import Author, Book | |
| # ── ДОДАВАННЯ ───────────────────────────────────────────────────────────────── | |
| author = Author.objects.create( | |
| name='Шевченко', | |
| birth_year=1814, | |
| rating=9.5 | |
| ) | |
| book = Book.objects.create( | |
| title='Кобзар', | |
| author=author, | |
| pages=325, | |
| price=150.00, | |
| published_year=1840, | |
| stock=10 | |
| ) | |
| # ── ПЕРЕГЛЯД ────────────────────────────────────────────────────────────────── | |
| Author.objects.all() # всі автори | |
| Author.objects.values() # як словники | |
| Author.objects.filter(rating__gte=7) # з рейтингом 7+ | |
| Author.objects.get(name='Шевченко') # один конкретний (кидає виняток якщо не знайдено) | |
| Book.objects.all() | |
| Book.objects.select_related('author').all() # з підтягуванням автора (JOIN, без N+1) | |
| Book.objects.filter(author__name='Шевченко') # книги конкретного автора | |
| # ── ОНОВЛЕННЯ ───────────────────────────────────────────────────────────────── | |
| # один запис | |
| author = Author.objects.get(name='Шевченко') | |
| author.rating = 10.0 | |
| author.save() | |
| # або одразу без fetch (один SQL UPDATE) | |
| Author.objects.filter(name='Шевченко').update(rating=10.0) | |
| # ── ВИДАЛЕННЯ ───────────────────────────────────────────────────────────────── | |
| # один запис | |
| author = Author.objects.get(name='Шевченко') | |
| author.delete() # видалить і всі його книги (CASCADE) | |
| # або одразу | |
| Author.objects.filter(birth_year__lt=1800).delete() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment