Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

An Overview of Models in Django

407 views

Published on

A talk delivered to the Philadelphia Python User Group on 09/17/15

Models form the backbone of most Django sites. They contain the fields and behaviors of the data your site is using. The proper planning and implementation of models is one of the first steps to creating powerful and reusable Django apps. It’s also crucial for avoiding pitfalls and complex workarounds down the line. In this talk you’ll hear about: -

• Django model fields and methods

• Model inheritance

• Relational databases

• Migrations

• How to access the data stored within your models

Published in: Internet
  • Login to see the comments

An Overview of Models in Django

  1. 1. An Overview of Models in Django
  2. 2. Michael Auritt • Director of Media Production at CorpU • Self-taught programmer • Twitter: @mauritt
  3. 3. Django djangoproject.com
  4. 4. Django • Models • Views • Templates
  5. 5. Django • Models - Manage our data • Views - Query the data • Template - Present the data
  6. 6. Django • Models - Manage our data • Views - Query the data • Template - Present the data
  7. 7. Models • The single definitive source of information about your website data • Uses Django’s Object-relational Mapper • Each model maps to a single database table • Each field maps to a column within that table
  8. 8. Talent Management The Happiness Advantage CorpU Promo My Video Portfolio Videos | About | Contact Supply Chain Management http://www.myvideoportfolio.com/videos
  9. 9. Supply Chain Management My Video Portfolio Videos| About | Contact http://www.djangodjunction.com/djangos/01 This course explores end-to-end supply chain management. This video takes a look at the main elements of a modern supply chain and…
  10. 10. Supply Chain Management My Video Portfolio Videos| About | Contact http://www.djangodjunction.com/djangos/01 TITLE DESCRIPTION Embed This course explores end-to-end supply chain management. This video takes a look at the main elements of a modern supply chain and…
  11. 11. models.py from django.db import models class Video(models.Model): title = models.CharField(max_length = 200) description = models.TextField() embed_key = models.IntegerField() date_completed = models.DateField()
  12. 12. id(primary key) title description embed_key date_completed Video
  13. 13. id title description embed_key date_completed 1 Ursa Motors In this video… 679210 2014-10-01 2 Sea Box Sea Box is a company that… 933750 2015-03-15 3 Critical Thinking In Critical Thinking… 876025 2014-09-23 4 CorpU Promo CorpU’s platform… 867302 2015-02-05 video
  14. 14. models.py from django.db import models class Video(models.Model): title = models.CharField(max_length = 200) description = models.TextField() embed_key = models.IntegerField() date_completed = models.DateField()
  15. 15. djangoproject.com Documentation Model Field Reference
  16. 16. models.py from django.db import models class Video(models.Model): title = models.CharField(max_length = 200) description = models.TextField() embed_key = models.IntegerField() date_completed = models.DateField()
  17. 17. title = models.CharField(max_length = 200)
  18. 18. hidden = models.BooleanField(default = True)
  19. 19. slug = models.SlugField(unique = True)
  20. 20. Validators • validate_slug • EmailValidator • URLValidator
  21. 21. Validators (validate = [email_validator])
  22. 22. models.py from django.db import models from django.core.exceptions import ValidationError def validate_embed(value): valid_embed = (checks embed at vimeo.com) if not valid_embed: raise ValidationError(‘That embed code does not exist at vimeo.com’) class Video(models.Model): embed = integerField(validators = [validate_embed])
  23. 23. Field Choices GENRE_CHOICES = ( (‘DOC’, ‘Documentary’ ), (‘PRO’, ‘Promo’), (‘NAR’,’Narrative’), ) genre = models.CharField( max_length = 3, choices = GENRE_CHOICES )
  24. 24. models.py from django.db import models class Video(models.Model): title = models.CharField(max_length = 200) description = models.TextField() embed_key = models.IntegerField() date_completed = models.DateField() hidden = models.BooleanField(default = True) slug = models.SlugField(unique = True)
  25. 25. Relationships • Many to One • Many to Many • One to One
  26. 26. Many to One One row of a database table relates to many rows of another.
  27. 27. title … client … Client: 01 … Client: 02 … Client: 01 … Client: 03 … Client: 01 … Client: 02 id name website … 01 … … 02 … … 03 … Video Client Many to One
  28. 28. Many to One class Client(models.Model): name = models.CharField(unique = True) website = models.URLField() class Video(models.Model): client = models.ForeignKey(Client)
  29. 29. Many to Many Many rows of a database table relate to many rows of another.
  30. 30. … role … role: Camera Op, Editor, Producer … role: Camera Op, Editor … role: Producer … role: Editor name … Camera Op … Editor … Producer … Video Role Many to Many
  31. 31. Many to Many class Role(models.Model): name = models.CharField(unique = True) class Video(models.Model): role = models.ManyToManyField(Role)
  32. 32. One to One One row of a database table relates to one row of another.
  33. 33. … file … File: 1 … File: 2 … File 3 … FIle 4 Video One to One id path 1 2 3 4 File
  34. 34. One to One class File(models.Model): drive = models.CharField() path = models.FilePathField() class Video(models.Model): file = models.OneToOneField(File)
  35. 35. $ python manage.py makemigrations
  36. 36. Migrations operations = [ migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('description', models.TextField()), ('embed', models.TextField()), ('company', models.ForeignKey(to='videos.Company')), ('roles', models.ManyToManyField(to='videos.Role')),
  37. 37. $ python manage.py migrate
  38. 38. Migrations operations = [ migrations.AlterField( model_name='company', name=‘slug’, field=models.SlugField(unique=True),
  39. 39. Migration Issues • Adding new fields without a default • Adding new unique fields • Changing relationships
  40. 40. Queries Returning Many Objects • Video.objects.all() • Video.obects.filter(client = ‘MasterCard’) • Video.objects.all().order_by(‘date_created’)
  41. 41. Queries Returning Many Objects MC_Videos = Video.obects.filter(client = ‘MasterCard’) MC_Ascending_Order = MC_videos.order_by(‘title’) MC_Descending_Order = MC_videos.order_by(‘-title’)
  42. 42. Queries Returning Many Objects MC_videos = Video.obects.filter(client = ‘MasterCard’) MC_videos = MC_videos.order_by(‘date_created’) MC_videos = MC_videos.exclude(Role = ‘Producer’)
  43. 43. Field Lookups field__lookuptype=value .filter(title__startswith=‘G’) .filter(date_completed__gte=datetime(2015,01,01)) .filter(title__contains = ‘Supply Chain’)
  44. 44. Queries Returning Single Objects • Video.objects.get(pk = 1) • Video.objects.get(title = ‘My Best Video’)
  45. 45. Queries • QuerySet API Reference in Django Docs • QuerySets are lazy • QuerySets are faster than using Python
  46. 46. Queries >>>from video.models import Video >>> v = Video.objects.get(pk = 1) >>> print(v) <Video: Video object>
  47. 47. Model Methods from django.db import models class Video(models.Model): title = models.CharField(max_length = 200) def __str__(self): return self.title
  48. 48. Queries >>>from video.models import Video >>> v = Video.objects.get(pk = 1) >>> print(v) <Video: Talent Management>
  49. 49. Model Methods class Role(models.Model): name = models.CharField(unique = True) class Video(models.Model): def is_full_stack(self): full_stack = True for role in Role.objects.all(): if role not in self.role.all(): full_stack = False return full_stack
  50. 50. Model Methods >>>from video.models import Video >>> v = Video.get(pk = 1) >>> v.is_full_stack() True
  51. 51. Views.py def detail(request, slug): try: video = Video.Objects.get(slug = slug) except video.DoesNotExist: raise Http404() else: context = {‘video’: video} return render(request, ‘videos/detail.html’, context)
  52. 52. Model Manager video.objects.all()
  53. 53. Model Manager video.objects.all() models.Manger
  54. 54. Thanks Further Reading • djangoproject.com • Two Scoops of Django (TwoScoopsPress.com) • Lightweight Django (O’Reilly)

×