Python and Django Lessons

Jun 25 2019

Picture here

It has been quite a while since my last post. The main reason is work.
However, it's thanks to this workload that I have something to post (I have a lot).
In my last post I discussed the difficulties of getting the project up and running. Now I'd like to cover some of the new challenges I've encountered and the things I've learnt.
This will primarily be Python and Django based.


First are Querysets, which are a powerful Django tool. They are powerful because they're basically SQL database queries that for the most part are executed once and don't take a great toll on your network/memory. For example:


queryset = Schedule.objects.filter(start_date__gte="2019-01-01")

Here we are querying Schedule objects in the database to filter for specific objects that have their start_date attribute greater-than-or-equal-to "2019-01-01". In SQL this would equate to something like:


SELECT "schedule"."uuid", FROM "schedules_schedule" WHERE "schedule"."start_date" >= 2019-01-01

Except the actual query SELECTS all the objects attributes, not just uuid.
With Q objects querysets can get more complicated because you can incorporate logical AND/OR into your queries. AND is represented as &, OR as |.
E.g:


Schedule.objects.filter(Q(user=self) | Q(contact=self)).distinct()

The distinct() method on the end insures that you're not returning duplicate objects (where an object may have both user=self and contact=self). Just another reason why Querysets are so powerful.


In addition to .filter() you can also use .exclude() or of course .all(). Also .get() can be used to fetch individual objects using their primary_key
E.g


Schedule.objects.get(pk=1)

to be continued...