Models Flashcards
field as primary key
from django.db import models
class Fruit(models.Model): name = models.CharField(max_length=100, primary_key=True)
Meta example
from django.db import models
class Ox(models.Model): horn_length = models.IntegerField()
class Meta: ordering = ["horn_length"] verbose_name_plural = "oxen"
raw sql
Person.objects.raw(‘SELECT * FROM myapp_person WHERE last_name = %s’, [lname])
Multi-table inheritance
from django.db import models
class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80)
class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False)
Abstract base class
from django.db import models
class CommonInfo(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField()
class Meta: abstract = True
class Student(CommonInfo): home_group = models.CharField(max_length=5)
proxy model
from django.db import models
class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
class MyPerson(Person): class Meta: proxy = True
def do_something(self): # ... pass
exact
Entry.objects.get(headline__exact=”Cat bites dog”)
Blog.objects.get(name__iexact=”beatles blog”)
contains
Blog.objects.filter(entry__headline__contains=’Lennon’)
F expression
> > > from django.db.models import F
|»_space;> Entry.objects.filter(number_of_comments__gt=F(‘number_of_pingbacks’))
Q objects
Poll.objects.get(
Q(question__startswith=’Who’),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
annotate
> > > from django.db.models import Q
above_5 = Count(‘book’, filter=Q(book__rating__gt=5))
below_5 = Count(‘book’, filter=Q(book__rating__lte=5))
pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)
pubs[0].above_5
23
pubs[0].below_5
aggregate
> > > from django.db.models import FloatField
Book.objects.aggregate(
… price_diff=Max(‘price’, output_field=FloatField()) - Avg(‘price’))
{‘price_diff’: 46.85}