py -m venv portfolio
portfolio\Scripts\activate.bat
py -m pip install Django
--------------------------------------------------
django-admin startproject <project_name>: Creates a new Django project with the specified name.
python manage.py runserver: Starts the development server, allowing you to view and test your Django application locally.
python manage.py startapp <app_name>: Creates a new Django app within your project, with the specified name.
python manage.py migrate: Applies any pending database migrations to synchronize the database schema with your models.
python manage.py makemigrations: Creates new database migration files based on changes made to your models.
python manage.py createsuperuser: Creates a new superuser account for accessing the Django admin interface.
python manage.py collectstatic: Collects all static files from your apps into a single location for deployment.
python manage.py test: Runs all the tests defined in your Django project.
python manage.py shell: Starts the Django shell, an interactive Python shell with access to your Django project.
python manage.py runscript <script_name>: Runs a custom Python script within the Django context.
Creating Objects:
python# Import the model class from myapp.models import MyModel # Create a new object obj = MyModel(name='John', age=25) # Save the object to the database obj.save()
Retrieving Objects:
python# Import the model class from myapp.models import MyModel # Retrieve all objects all_objects = MyModel.objects.all() # Retrieve a specific object by primary key obj = MyModel.objects.get(pk=1) # Retrieve objects based on a filter condition filtered_objects = MyModel.objects.filter(name='John')
Updating Objects:
python# Import the model class from myapp.models import MyModel # Retrieve an object obj = MyModel.objects.get(pk=1) # Update the object's attributes obj.name = 'Jane' obj.age = 30 # Save the updated object obj.save()
Deleting Objects:
python# Import the model class from myapp.models import MyModel # Retrieve an object obj = MyModel.objects.get(pk=1) # Delete the object obj.delete()
Querying with Conditions:
python# Import the model class from myapp.models import MyModel from django.db.models import Q # Retrieve objects matching a condition objects = MyModel.objects.filter(age__gte=18) # Retrieve objects matching multiple conditions using Q objects objects = MyModel.objects.filter(Q(name='John') | Q(age__gte=30))
Related Objects:
python# Import the model classes from myapp.models import Author, Book # Retrieve all books written by a specific author author = Author.objects.get(name='Jane Doe') books = author.book_set.all() # Retrieve the author of a specific book book = Book.objects.get(title='My Book') author = book.author