DEV Community

suyaa
suyaa

Posted on

Django SQL cheatsheet

SELECT

filtering

# filter students by ID
Student.objects.get(pk=1)

# get array of students
Student.objects.filter(enrolled=True)

# filter by pk
Student.objects.filter(school__pk=1) # school_id = 1

# is null
Student.objects.filter(photo__isnull=True)
Enter fullscreen mode Exit fullscreen mode

order by, distinct

# get distinct last_name
Student.objects.order_by("last_name").distinct()

# order by desc/multiple fields
Student.objects.order_by("-pk", "last_name")
Enter fullscreen mode Exit fullscreen mode

get result as an array

>>> Student.objects.values_list("last_name", flat=True)
["Smith", "Johnson", "Williams"]
Enter fullscreen mode Exit fullscreen mode
  • values return a dict
  • values_list returns a tuple, but with flat=True option returns an array

see also: https://stackoverflow.com/a/41085356/9644490

count

>>> Student.objects.filter(school__pk=2).count()
120
Enter fullscreen mode Exit fullscreen mode

exists

Student.objects.filter(photo__isnull=True).exists()
Enter fullscreen mode Exit fullscreen mode

CREATE

s = Student(last_name="Smith", first_name="John", school_id=1)
s.save()
Enter fullscreen mode Exit fullscreen mode

UPDATE

s = Student.objects.get(pk=1)
s.last_name="Wilson"
s.save()
Enter fullscreen mode Exit fullscreen mode

DELETE

s = Student.objects.get(pk=1)
s.delete()
Enter fullscreen mode Exit fullscreen mode

all, none

Student.objects.none()
Student.objects.all()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)