Junior — Middle
How can data be retrieved from a database using the Django ORM framework?
sobes.tech AI
Answer from AI
In Django ORM, methods of model managers and QuerySet are used to retrieve data from the database. The main ways are:
- Get all objects of a model:
from myapp.models import Product
products = Product.objects.all()
- Filter by conditions:
cheap_products = Product.objects.filter(price__lt=100)
- Get a single object (if you are sure it exists):
product = Product.objects.get(id=1)
- Use methods for sorting, aggregation, selecting specific fields:
sorted_products = Product.objects.order_by('name')
names = Product.objects.values_list('name', flat=True)
Thus, ORM allows working with the database through Python objects without writing SQL directly.