Friday, July 12, 2024

Django models relationships

 from django.db import models


# One-to-One Relationship

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

    bio = models.TextField()


# Many-to-One Relationship

class Post(models.Model):

    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')

    title = models.CharField(max_length=200)


# Many-to-Many Relationship

class Course(models.Model):

    students = models.ManyToManyField(Student, related_name='courses')

    title = models.CharField(max_length=200)


# Summary of Relationship Types

# | Relationship Type   | Model Field Type         | Description                          |

# |----------------------|--------------------------|--------------------------------------|

# | One-to-One           | OneToOneField           | Each instance relates to one instance. |

# | Many-to-One          | ForeignKey              | Many instances relate to one instance. |

# | Many-to-Many         | ManyToManyField         | Many instances relate to many instances. |




Here’s a summary of the most common Django model queries you can use in a single window for quick reference:

```python
# 1. Import your model
from myapp.models import Author

# 2. Create a new object
author = Author(first_name="John", last_name="Doe")
author.save()

# 3. Retrieve all objects
authors = Author.objects.all()

# 4. Retrieve a single object by ID
author = Author.objects.get(id=1)

# 5. Filter objects (e.g., by last name)
authors = Author.objects.filter(last_name="Doe")

# 6. Exclude objects
authors = Author.objects.exclude(last_name="Doe")

# 7. Retrieve the first and last object
first_author = Author.objects.first()
last_author = Author.objects.last()

# 8. Order results (ascending or descending)
authors = Author.objects.order_by('last_name')
authors = Author.objects.order_by('-last_name')

# 9. Limit results (get the first 10)
limited_authors = Author.objects.all()[:10]

# 10. Field lookups (e.g., contains, exact match)
authors = Author.objects.filter(first_name__icontains="oh")
author = Author.objects.get(first_name__exact="John")

# 11. Count objects
author_count = Author.objects.count()

# 12. Check if a QuerySet contains data
exists = Author.objects.filter(last_name="Doe").exists()

# 13. Update an object
author = Author.objects.get(id=1)
author.first_name = "Jane"
author.save()

# 14. Delete an object
author = Author.objects.get(id=1)
author.delete()

# 15. Aggregation (e.g., count)
from django.db.models import Count
author_count = Author.objects.aggregate(Count('id'))

# 16. Access related objects (ForeignKey or ManyToManyField)
books = author.book_set.all()  # Reverse ForeignKey relation
books = author.books.all()  # Many-to-Many relation

# 17. Chaining queries (e.g., filter, order, limit)
authors = Author.objects.filter(last_name__icontains="Doe").order_by('first_name')[:5]
```

authors = Author.objects.raw('SELECT * FROM myapp_author WHERE last_name = %s', ['Doe']) 

This is a compact and practical summary of common Django model queries for use in the shell.

Django Models all queries and commands

 # Basic Queries

MyModel.objects.create(field1=value1, field2=value2)

MyModel.objects.all()

MyModel.objects.filter(field=value)

MyModel.objects.get(field=value)

MyModel.objects.exclude(field=value)


# Querying with Conditions

MyModel.objects.filter(field1=value1).filter(field2=value2)

from django.db.models import Q

MyModel.objects.filter(Q(field1=value1) | Q(field2=value2))

from django.db.models import Count

MyModel.objects.annotate(num_related=Count('related_model'))

from django.db.models import Avg

MyModel.objects.aggregate(Avg('field'))


# Ordering and Slicing

MyModel.objects.order_by('field')

MyModel.objects.order_by('-field')

MyModel.objects.all()[:5]


# Advanced Queries

MyModel.objects.select_related('related_model')

MyModel.objects.prefetch_related('related_model')

MyModel.objects.values('field1', 'field2')

MyModel.objects.values_list('field1', flat=True)


# Existence Checks

MyModel.objects.filter(field=value).exists()


# Counting and Aggregating

MyModel.objects.count()

MyModel.objects.aggregate(Sum('field'))


# Updates and Deletes

MyModel.objects.filter(field=value).update(field2=new_value)

MyModel.objects.filter(field=value).delete()


# Other Useful Queries

MyModel.objects.distinct('field')

MyModel.objects.raw('SELECT * FROM myapp_mymodel WHERE field = %s', [value])


# Complex Queries

from django.db.models import OuterRef, Subquery

subquery = MyModel.objects.filter(field=OuterRef('related_field'))

MyModel.objects.filter(field__in=Subquery(subquery.values('id')))


# Aggregation Examples

MyModel.objects.aggregate(

    avg_field=Avg('field'),

    total_field=Sum('field'),

    count_field=Count('id')

)


# Using F Expressions

from django.db.models import F

MyModel.objects.filter(field=value).update(field2=F('field2') + 1)


# Performing Transactions

from django.db import transaction

with transaction.atomic():

    MyModel.objects.create(field=value)

    MyModel.objects.create(field=value2)


## All commands for django app

# Basic Commands
python manage.py runserver              # Start development server
python manage.py startproject <name>   # Create new Django project
python manage.py startapp <app_name>   # Create new app
python manage.py check                 # Check for issues
python manage.py diffsettings          # Show differences from default settings

# Database & Migrations
python manage.py makemigrations         # Create migration files
python manage.py migrate                # Apply migrations
python manage.py showmigrations         # List migrations and status
python manage.py sqlmigrate <app> <id>  # Show SQL for a migration
python manage.py flush                  # Reset DB (delete all data)
python manage.py inspectdb              # Generate models from existing DB
python manage.py dbshell                # Open DB shell

# User Management
python manage.py createsuperuser        # Create admin user
python manage.py changepassword <user>  # Change user password

# Testing & Debugging
python manage.py test                   # Run tests
python manage.py shell                  # Django Python shell

# Static & Media Files
python manage.py collectstatic          # Collect static files
python manage.py clearsessions          # Clear expired sessions

# Deployment Support
python manage.py check --deploy         # Check deployment best practices

# Custom Commands
python manage.py <your_command>         # Run custom management command

virtual environment on python on Ubuntu

 # 1. Update system and install Python tools sudo apt update && sudo apt install python3-pip python3-venv -y # 2. Setup Django in a ...