Retrieve all objects
MODEL.objects.all()
— Return a QuerySet containing all MODEL objects- QuerySet is a iterable
1 | from heritagesites.models import HeritageSite |
Select from direct foreign-key relationships
MODEL.objects.select_related(*fields)
— select direct foreign-key relationships
1 | from heritagesites.models import CountryArea |
** Passing multiple arguments to select_related
1 | from heritagesites.models import CountryArea |
Filter
- AND:
objects.filter(<condition_1>, <condition_2)
queryset_1 & queryset_2
filter(Q(<condition_1) & Q(<condition_2))
__startwith(value)
— select objects with field start with value
1 | from heritagesites.models import CountryArea |
- OR:
queryset_1 | queryset_2
filter(Q(<condition_1>) | Q(<condition_2))
- NOT:
exclude(<condition>)
filter(~Q(<condition>))
1 | # OR |
Show specific fields
.values
— show specific columns1
2
3# Show specified fields
ca = CountryArea.objects.filter(country_area_name__startswith='China').values('country_area_name','iso_alpha3_code')
# ( or use .only)
Subquery
Select all country area with SubRegion in ‘Eastern Asia’
1 | sr = SubRegion.objects.filter(sub_region_name = 'Eastern Asia') |
Join
In Django ORM, select joined objects is used as __
, i.e: dev_status__dev_status_name
select_related
— used when one-one foreign keys
1 | ca3 = CountryArea.objects.filter(dev_status__dev_status_name = 'Developed') |
Join across multiple tables
1 | ca = HeritageSite.objects\ |
Sort Data and imposing limits
Sort the QuerySet by area_hectares
(descending), followed by site_name
(ascending)
1 | from heritagesites.models import HeritageSite |
Aggregating Data
- Count
1 | from django.db.models import Count |
- Group by and count
Return count of developed vs developing countries/areas in Sub-Saharan Africa
1 | from django.db.models import Count |
- Max, Sum
1 | from django.db.models import Max |
Annotation (Equivalent of GROUP BY
in SQL)
Group regions by development status
1 | loc = Location.objects\ |