Skip to content

Instantly share code, notes, and snippets.

@mthri
Last active February 27, 2020 21:28
Show Gist options
  • Save mthri/e30ad6884acc722bcba5b71ea0ba23c1 to your computer and use it in GitHub Desktop.
Save mthri/e30ad6884acc722bcba5b71ea0ba23c1 to your computer and use it in GitHub Desktop.
Django ORM

Making queries with Django ORM

Official tutorial

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField()
    number_of_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

Limiting QuerySets:

Entry.objects.order_by('headline')[0]
SELECT foo FROM bar LIMIT 1

Field lookups:

Entry.objects.filter(pub_date__lte='2006-01-01')
SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
Entry.objects.get(headline__exact="Cat bites dog")
SELECT ... WHERE headline = 'Cat bites dog';

iexact A case-insensitive match.
Would match a Blog titled "Beatles Blog", "beatles blog", or even "BeAtlES blOG".

Blog.objects.get(name__iexact="beatles blog")
Entry.objects.get(headline__contains='Lennon')
SELECT ... WHERE headline LIKE '%Lennon%';

Escaping percent signs and underscores in LIKE statements:

Entry.objects.filter(headline__contains='%')
SELECT ... WHERE headline LIKE '%\%%';

Complex lookups with Q objects:

Poll.objects.get(
   Q(question__startswith='Who'),
   Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

SELECT * from polls WHERE question LIKE 'Who%'
   AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment