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.

No comments:

Post a Comment

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 ...