Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Best Practices With Django

Best Practices With Django

Over this talk, I spoke about some best practices with Django which we might have been overlooked.

Avatar for Damilola Ogungbesan

Damilola Ogungbesan

November 02, 2019

Other Decks in Technology

Transcript

  1. More about me... • Software Developer based in Lagos. •

    I work as a Full-stack Developer @ Lepsta Inc. Where we develop the next generation version control system. On the internet: • Lepsta: https://www.lepsta.tech • Twitter: @horiyomi4u • Github: https://github.com/horiyomi
  2. Agenda 1. Briefly On Django 2. Virtual environments / Bootstrapping

    Django 3. Settings 4. Models 5. Queryset 6. Q & A
  3. Simply put “It’s a framework that makes our life easier

    building web apps using one of the most simplest programming language to pick up (Python)”. Plus it comes with with some out of the box features that most, if not all web apps would need such as • Authentication(Can be extended and customized) • Admin system that works right out of the box e.t.c Django As A Framework BRIEFLY ON DJANGO
  4. Effective Use Of Virtual Environments There are couple of virtual

    environments packages python • Virtualenv • Venv • Pipenv VIRTUAL ENVIRONMENTS / BOOTSTRAPPING DJANGO
  5. Using Multiple Setting Files A typical Django project directory after

    running the bootstrapping command for a project using django-admin startproject pycon . SETTINGS
  6. Some Reasons Why • Separating different environment configurations • Makes

    your life easier with deployment to various environment such testing, staging, production environments Caveat: You can’t run your project again with just the normal command of python manage.py runserver You need to specify which settings file you are using “--settings” flag python manage.py runserver --settings=pycon.settings.dev SETTINGS
  7. NO!

  8. 1. Effective use of the “Meta” class 2. Effective use

    of queryset managers 3. Model methods Best Practices with Django Models
  9. Using Meta Class class Event(models.Model): title = models.CharField(max_length=255) ... start_date

    = models.DateField() end_date = models.DateField() class Meta: db_table = "event" verbose_name_plural = "events" ordering = ["start_date"]
  10. Meta Class Options db_table: This is for specify the table

    human friendly table name. verbose_name_plural: This is useful in the admin that django provided for the description of the model instance name. ordering: With this you can specify the order you would like record to be sorted when you query abstract: This is useful when you need to a common model across multiple, hence the model will not have it own table, but it fields will be extended to the model(s) inheriting it.
  11. class TimeStamp(models.Model): created_date = models.DateTimeField( auto_now_add=True, editable=False) updated_date = models.DateTimeField(

    null=True, blank=True, editable=False) deleted_at = models.DateTimeField(blank=True, null=True) class Meta: abstract = True
  12. class Event(TimeStamp): title = models.CharField(max_length=255) ... start_date = models.DateField() end_date

    = models.DateField() class Meta: db_table = "event" verbose_name_plural = "events" ordering = ["start_date"]
  13. Using Model Methods Model methods are very handle methods which

    we can use to keep our code DRY 1. We can use it to wrap business logic 2. We can use for easy data access 3. It reduces database lookup, as query that are not callable are cached (e.g, using @property decorator in on a model method, will make the method not to be a callable)
  14. Some Optimized Way Of Querying Django comes with a very

    handy ORM(object relational mapper), which is what we use in querying for data.
  15. Don’t do this if you have no use of the

    data instance events = Event.objects.filter(...) total_event_count = len(events) Instead use the queseryset callback method “count” events = Event.objects.filter(...) total_event_count = events.count() GOTCHA!
  16. GOTCHA! Don’t do this if need to access related fields

    value events = Event.objects.filter(...) if event.speaker.id: Pass Instead use the queseryset callback method “count” events = Event.objects.filter(...) if event.exists(): pass
  17. Convenient But Might Be Costly It’s very tempting to do

    this, events = Event.objects.all() when you need to get all record on a table, it’s important to know that django orm is will retrieve all the columns from the database and use them to populate the model fields, which is fine if only we intend to use all the fields value.
  18. With values we get a queryset of intended fields declared

    only Event.objects.values('title','start_date') <QuerySet [{'title': u'PyCon NG',u'start_date'}]>
  19. With values_list we get a queryset of intended fields declared

    only as tuples Event.objects.values_list('title','speaker__name') <QuerySet [(u'PyCon NG'',u'Damilola'), (u'...')]>
  20. With “values_list” we can also get queryset of intended field

    as list using the “flat=True” Caveat: If there is only one field Event.objects.filter(speaker=speaker).values_list('id', flat=True) <QuerySet [123,2,....]>
  21. select_related With select_related we can retrieve related field with a

    single query. event = Event.objects.select_related("speaker").all()