Skip to content

Instantly share code, notes, and snippets.

@rob-kistner
Last active October 4, 2020 15:10
Show Gist options
  • Select an option

  • Save rob-kistner/657c57ec2adf007c7f4fa70178c000f8 to your computer and use it in GitHub Desktop.

Select an option

Save rob-kistner/657c57ec2adf007c7f4fa70178c000f8 to your computer and use it in GitHub Desktop.
Django - ORM
# Common CRUD Operations using Django
# ----------------------------------------
# in an app's models.py…
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
address = models.TextField()
# ----------------------------------------
# in views.py…
# ----------------------------------------
# Create / Insert Query
from .models import Person
# Save directly onto a Person instance
obj1 = Person(
first_name="Rob",
last_name="Kistner",
address="1060 West Addison"
)
obj1.save()
# using the objects.create function
obj2 = Person.objects.create(
first_name="Rob",
last_name="Kistner",
address="1060 West Addison"
)
# ----------------------------------------
# Get Query
# assuming known the id
obj1 = Person.objects.get(id=1)
# ----------------------------------------
# Update Query
obj1 = Person.objects.get(id=1)
obj1.first_name = "Adam"
obj1.save()
# ----------------------------------------
# Delete Query
# accessing via .get
obj1 = Person.objects.get(id=1)
obj1.delete()
# accessing using .fitler
Person.objects.filter(id=1).delete()
# ----------------------------------------
# Filtering
# filter query
# icontains is case-insensitive
obj_list = Person.objects.filter(first_name__icontains="adam")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment