Back to the video

Home on the range with Django - getting comfortable with ranges and range fields with Jack Linke

Transcript

By Jack Linke, Speaker 2, Speaker 3, Speaker 4. From DjangoCon US 2022. Published November 24, 2022.

Watch the video Markdown version 4,852 words · auto-generated · en

Summary

PostgreSQL range types let Django applications represent related lower and upper bounds as one field, preserving boundary information and allowing the database to reject invalid backwards ranges. Jack Linke explains PostgreSQL’s inclusive/exclusive range semantics, Django and psycopg2 range fields, and lookups such as overlap, contains, adjacent, startswith, and endswith, showing how they simplify queries compared with separate start and end columns. Through a pool-reservation example, he covers indexing, forms, migrations, custom range types, and practical limitations such as weak Django admin support.

Transcript

Automatically transcribed, so expect mistakes in names and technical terms. Filler words are removed.

0:20 Introduction to PostgreSQL Ranges

Jack Linke

So I'm Jack. I this is actually my second year speaking with you all. Last year I was honored to have the opportunity to speak about HT HTMX. Use with Django during the virtual twenty twenty-one conference. So as you can see on the screen, I run a business called WaterVise. And I am all of these things at the bottom of the screen, but I'm not sure that I've mastered any of them. So we'll see. Alright, so again, my talk is Home on the Range with Django, and we're going to talk about using Postgres range types. With your Django applications and why you might want to consider doing so.

So a few disclaimers this These topics are maybe a little more intermediate. Some of you more advanced folks will probably think this is old hat, but And this is also Postgres specific. So if you're using a different database backend, this really won't apply to you, but hopefully in a future project you'll consider Postgres. It's a pretty awesome database. So the goals here, hopefully we'll learn why ranges can be more useful than having distinct start and end or min and max fields in your project. You'll get familiar with some of the terminology. We'll see a number of approaches to using and querying with ranges. And I'll give you some resources that

1:53 The Case for Range Fields

Jack Linke

will help you as you move forward if you'd like to use ranges in your app. applications. So real life ranges are used all around us all the time. It's just not something we generally think about a lot. You know, daily temperature highs and lows. Things like the range of calories in a set of meals or business hours for a set of businesses. So we use them all the time. It's something that is in most of our applications in one way or another. The history of range fields, they've been around since 2011, the range types in Postgres and since twenty fifteen Django

has had support for these When we look at projects, often we have kind of like I mentioned, a start and a stop field. So a start date and an end date, or a minimum date and a maximum date. Querying with these start and stop values can get really complicated and challenging really quick. It's not always super intuitive, and we'll we'll look at some of that here. So some comparisons when we look at constraints, for instance, having two separate fields, the database doesn't know that they're related in any way. So unless you add specific constraints to say, hey you know, the min value needs to be lower than the max value the database doesn't know that.

So you have to build some logic where you end up with weird things like ranges from $200,000 to $140,000, which just doesn't make sense. And then when it comes to preventing overlaps, if you want to prevent overlaps in your database, you have to kind of trick the database into treating those two fields as a single field to do this effectively with a exclusion constraint. So probably not super easy to see and you don't need to see the details really on this one, but this is everything that's required to add the functionality I just mentioned. And we add a check constraint on here to prevent a lower value from being larger than the higher value, and an exclusion constraint to prevent some overlaps.

4:21 Range Field Advantages

Jack Linke

At the top you can see we have to add an additional TSTZ range function so that the database can again kind of get tricked into thinking that that period start and period end, those two fields are will be treated as a single field in the constraint. Comparatively using a range field We just have one field and we're storing a good amount of information in a single field. The lower value, the upper value, and some information about the boundaries of that range. The database knows that they're all related. By default, Postgres won't let you put a lower value in the upper value spot. So you can't have backwards ranges.

So right off the bat, it comes with some benefits there that you don't have to manually do that for the database. So you can see we end up with a much smaller the same equivalent portion of the of the model here. So some comparisons with queries. Again you have to include both fields So these are often unintuitive. I found it really challenging as a beginner to understand how to do this right because you end up with things like this. In reality, the event start, so if we have an event model with an event start and an event end, and we want to look at how that

You know filter that down to over to The instances that it overlaps with in a 12-hour period, you have to do event start is less than the end of that period you're looking for, and event is Greater than or equal to the end is greater than or equal to the start of that period that you want. And that just as a beginner, that just doesn't make a whole lot of sense. When you when you kind of I had to literally draw it out visually to understand that when I started out four or five years ago. So using a single intuitive lookup instead, you end up with this. If we have an event period which is a date-time range field.

6:42 Range Boundaries and Intervals

Jack Linke

Then we just have to look at does it overlap? It's as simple as that. There's no messing around with starts and ends and you know multiple lookups. Just very simple. Does it overlap? So to make sure we all understand what these different lookups mean, we're gonna go back to elementary school but there won't be any tests, I promise. A few things right off the bat. If you come from like a math background or if you remember back in elementary school, you had the number line. And you have intervals and they could be closed intervals, open intervals. So the terminology that Postgres uses may not be what you're familiar with, but these are kind of the

equivalents. And then this is what it looks like, right? So on the very top, we have from the number one to seven, if this is looking at an integer range. We have from the number one to seven, but that's exclusive of both of those. So that that range really includes the numbers two through six. And I'm I'm putting this up here. Again, this is not a test. This is just to make sure we all understand before we go on That second one down is really the one we're going to kind of focus on, and that's what Postgres and Django use by default, is a inclusive and exclusive range. So when you look at this value, it includes the number one, that second one down again.

It includes the number one, but it does not include the number seven. And that is the default that Postgres uses. Another way to look at it is just like this. Again, the second one down being that in this case 1 is less than or equal to x and 3 is greater than x. So we are not including 3. It is excluded. Kind of boring stuff, but here we go into the visuals of it. So I put together several slides here. Again, I'm I'm very much a visual person and I know I'm not alone in that.

9:03 Range Query Lookups

Jack Linke

So sometimes seeing how these different lookups that can be used when you're querying ranges, seeing it visually can help. So this one is the first we're looking at when a range overlaps a range. And as you can see, the two on the bottom, the one where it's zero inclusive to exclusive, it's It's almost touching two, but it's not touching two. It doesn't include two. So that one would get filtered out of this filter. Contains is another one. And the nice thing about contains is that it can be used with a single element or a range.

So in this case, we're trying to filter And return any instances that contain the element of interest. So the number four there, the integer four is our what we want to filter on. So we're looking at anything that contains that, any of our instances that contain that. And the first two there, 0 to 8 and 4 to 9, do contain it. And again, 4 to 9, because that bottom number is inclusive, it includes that 4. Like I mentioned, you can also use contains with a range. So in this case, a range containing another range.

And then contained by just reverses that relationship. So in this case, we're looking for anything that's within the range of one to eight, with eight being excluded. And this also can be used with a range compared to a range. Adjacent two lets you identify things that are right next to the range you're interested in. So if your hours of operation are from eight to ten, And you want to find out if there's anything immediately after that closing time this is what you would use. So the range of interest here

11:21 Django Range Field Types

Jack Linke

excludes the number six, which is why those two on the outside that are green are the way they are. And then fully less than and fully greater than just really mean is it all the way to the left of or all the way to the right of the range that we're looking at? So, how do we actually use these? The Psycho PG2 Extras package provides some tools for translating between Django fields and the range types in Postgres. And there's a couple things to keep in mind here. So we've got numeric range and date range, and there's a couple on the next page.

When it comes to integers and dates, those are you know discrete values. All of the other ones, and big inter range, sorry, decimal ranges and on this next page, date time range and date time tz range. Those are not discrete they are continuous so you can have continually smaller you know periods be between things And that that can be important as we'll talk about later. So the date time range, unless you're using naive date times, you're probably never going to use that. I wouldn't recommend it. For most things if you're using time zones use the time zone TZ range from cycle

PG to extras. And as you can see here, this shows the equivalent Postgres and equivalent Django fields that these map to. So when we're defining range fields in a Django model, this is some examples here. So using integer range field, we can have it with no additional information. It's just an empty range We can use a tuple for a default, or we can use a numeric range. Again, that numeric range is coming from the Psycho PG to Extras package. And we can also specify the bounds we're using here. So again, I mentioned that Postgres

by default uses a Inclusive lower and exclusive upper, but you can specify these. It gets a little weird and it's It's something I'm not going to go into depth here because you kind of got to wrap your brain around when it's appropriate to do so. And then there's some lookups that Django provides that are based on the range bounds themselves. The most useful ones that I use all the time are the starts with and ends with. These let you query on the lower and upper portions of a range.

So a few examples here of instance creation. Here we're defining three different ranges. So my first range is using a numeric range from that extras package. And we've defined the lower value as none, the upper value as none, and the bounds. I just kept it with the default inclusive exclusive. The second range down there, we're just using a tuple, one and five. And the third one, we're also using numeric range, but we have a lower value of seven and an upper value of none. We create a few objects in my model using those. And then on this next page, you can see how we are using the

starts with and ends with. So if we look at starts with, we can add on additional lookups like greater than, less than, greater than, equal to. In this case, we're looking for any of those three that is greater than three in that that lower value. And obviously the last one fits that category. And then ends with greater than ends with equals five there. The only one that matches with that is the second range. You can also create your own range types. Django and Postgres provide the functionality to do that. One example that you might be interested in, for instance, is

Taking the generic IP address field and extending it to be a range of IP field IP addresses. So if you're doing work you know on a network and you need to record a number of ranges You know, this customer is operating from this IP address to this IP address. You can use the ranges to extend it to do that. And again, I'm not going into detail with that because we are limited on time, but the Django docs do a pretty good job of getting you started on how to extend the ranges for your own types. When it comes to indexing, pretty much stick to the gist

16:42 Pool Scheduling Example

Jack Linke

index or the B tree index. Those are the two that really cover the majority of the lookups that we're interested in. Some of the other indexes like GIN don't don't cover any of the range stuff. So the kind of the big thing that I'm hoping to bring to this talk is a project I I've been developing. It's it's not super beautiful, but it's simple and hopefully will be useful to you all. So it's a pool scheduling application for a municipality. And the idea here is that we have

a bunch of users and a bunch of pools. And each pool can have multiple lanes, multiple lockers, and maybe closed here and there. And then users can make reservations for these lanes and lockers. This is a little more detailed view of the schema for the database. And as you can see, I've tried to throw in several ranges here. As much as possible. So we have a couple integer range fields that are the depth and business hours for the pool, the maximum number of swimmers that a lane can have. The reservations are from one time period to another date time period, I should say.

And let me pull it up. So this is still somewhat of a work in progress, but I have a number of examples in here already. Again, the goal here was really to help others that were in the same boat as me in the past. I tried to find documentation and details for how to use range fields and I as much as I love Django docs for just about everything when it comes to range fields if you're not familiar with them, it can be a real challenge to find useful stuff in the docs or even on like Stack Overflow. There's just there's not a whole lot of examples out there. So in this case, I've tried for every page in this in this project, and you can go to

the URL that I'll show you at the end. And it's just a Docker compose project. But for each one, we've got some details about what we're doing. So in this case, we're just listing the pools and the business hours. And for each time period here for our business hours, we're using dot lower. So pool. business hours dot lower and pools pool. business hours. upper to give the actual value here. And then we've you know zero padded it to make it pretty.

Again, lots of examples here. So to show how you know the reservations that are greater than eight hours in length. You can see here I've just got some example data that's been mocked into the database. We have four reservations, four reservations for lanes that are over a period of eight hours. And when we go to the code notes, again it goes into some detail here, and I encourage you all to look at this later. But we we're essentially using the ends width and start starts with lookups that I mentioned earlier and filtering to annotate each one of those

With the start time subtracted from the end time. And then we add a filter after that to get the delta, any delta that is greater than a time delta time zone time delta of eight hours. For reservations this week, either starting on a Sunday with this first example or a Monday with the second example. We can see the results in this calendar here. This shows all for this week. So starting on the 16th and going towards the end to the end of the week.

There are all of our examples. And for this one, created just a simple utility in a separate file to pull the start and end. Date time for this week and next and then filtering on that similar to the other one using the overlap this time. So as I mentioned before, overlap simplifies your Queries when it comes to taking one date time range and another date time range and identifying if they overlap or not, this makes it very simple.

Also showing here are examples for all the reservations this month. Any past reservations, reservations year to date or from now till the end of the year. This application has just a simple check-in checkout functionality. For reservations, you can compare then if the reservation, if they've checked in for the reservation or checked out, or if they haven't, this will show you if there's an overdue start. So for instance here, these three reservations, they never checked in. And that is performed by looking at again the starts width and then using less than now.

23:01 Range Fields in Forms

Jack Linke

And for the actual check-in date time range starts with, and we look for something that's null. So they never checked in. One of the things that was really challenging as a beginner also was working with date times. And other ranges when it came to forms. So I have three different examples here of ways you might approach using ranges in your forms. First being manually rendering the values. So in this case, I manually put a input tag

into the template. It's not actually using forms. This is using HTMX so that when I select some date times here. And apply. We're using HTMX to send a post request, which then the input or I'm sorry, the response from that gets input into a div. And displayed here. And as somebody who has come to really like HTMX, I think that might just be the easiest way. But it doesn't come with you know, the validations that that Django Forms does. So if we look at

Django Forms This example is very similar, but what we've done is use a text field, and then I'm cleaning in the back end. So it looks just about the same. When we apply, you get the results. But again, we've got the form with a char field in this case and a text input for the widget And then we are cleaning that that text to convert it into an actual value that we can use. In this case We've we've attached

using jQuery, we've attached a date time range picker. Actually all these examples do. You could use obviously you know a different JavaScript library or different means of displaying that date time range, but that was convenient here. And then the last one is to use a true date time range field from Django. And in this case, it displays it as a split multi-widget. With two different date time fields. And so again, I just attached using the same I am using bootstrap date range picker here. You could use whatever you like, but We select a range, submit, and

26:07 Range Field Pitfalls

Jack Linke

we get some results. We've got another number of other examples that are still in progress that will show some more advanced filtering and database work when it comes to using ranges. But hopefully this will be a good start to look at and beneficial to you all. There are some pitfalls when it comes to using ranges. Support in the Django admin is not really great. And there's actually a ticket open that kind of talks about that. The concern was that

You know modifying Django admin to bring in contrib Postgres content to change it would be problematic and kind of mixing things that maybe shouldn't be mixed. You can of course extend the default multi-widget used in Django's admin. With your own template and then use a similar technique to what I was showing earlier and you know attach a picker of some sort. But by default, you just get these text boxes and it can be a little off-putting, I guess, trying to modify your ranges in the admin

Trying to use lower and upper as callables. They're not callables. So when it comes to querying, you can use the lower and upper database functions to specifically pull out those pieces of the range. And then when it comes to using lookups, again you can use starts with and ends with to pick out those pieces. And using F with the extra classes, F is You know, used within Django to refer to the contents of a field. But the Psycho PG2 extra classes are not Django classes, and they are not

Postgres types, they are kind of that translation layer between the two. So you may have to use cast if you're if you're trying to pick out for instance to conduct aggregation or annotation and you would typically use F, you may have to use cast and cast those to an actual Django range type to be able to do that So there are a number of resources when it comes to working with ranges. So the Psycho PG2 extras documentation itself goes into some good detail about how you use those different classes

29:09 Resources and Supporting Packages

Jack Linke

and the functionality they provide. Obviously the Django docs is a good place to start and I've benefited a lot from looking at the tests as well. When it comes to understanding kind of any deeper thing in Django, or probably Python as a whole, looking at tests can be a huge benefit. This talk and the example project that I mentioned are on GitHub, and I encourage you to grab that and There 's very simple instructions for using it with Docker Compose to pull it up for yourself. And then a couple packages that that I have worked on in the past that

I found very useful when it comes to working alongside ranges are the range merge package and it just takes Postgres 's range merge function for aggregates and allows you to do things like if you're filtering and you have one range way over here and one range here. So say from one to two and from seven to eight. Range merge allows you to get from one to eight returned, a single full range that that covers the entirety of everything that's been filtered. And then Django Generate Series, very similarly, just helps you use Postgres 's generate series to make sequences, which can be really helpful if you want to, for instance, have a denormalized

Database table of bucketed times or bucketed integer ranges. If you don't want to drop down to raw SQL, you can use that package to generate those. All right, and one final thought because you got to leave this on a tacky last thing. A man works hard to name an interval equal to 24 hours. So he calls it a day.

31:22 Questions

Speaker 2

So we do have a bunch of time if anyone would like to ask a range of questions. Well actually one per

Jack Linke

You should have given the talk.

Speaker 2

I did one yesterday Hi

Speaker 3

Jack, thank you. It's r really good. I had a sort of half thought. Was it say I've got a model with two daytime fields and I haven't used a range. Can I query with a range object? Is that

Jack Linke

Say that again.

Speaker 3

So I've got a model and I've got to start it out and I've finished that because I didn't think oh I know I'm gonna use a range field. Can I is there a sort of way I can query with a range object against that existing

Jack Linke

So you can and I'm gonna go back to towards the beginning when we were looking at the constraints. So this example from Django's docs actually about Postgres constraints. Here they use a TSTZ range to use that function within the Postgres database. And so you can use very similar to what they do down at the bottom, or I guess it's kind of in the middle, is they have an expression there where they're using that function and then combining those two. Period start and period end being the two distinct fields here. And then they're using range boundary. That just gives you the default

inclusive exclusive bounds. So that that's generally how you would accomplish that.

Speaker 4

thanks for the talk. I have several models that have start and end dates that could have been ranges what's the best strategy for converting a model to having a range instead of two fields?

Jack Linke

Good question. I cheated. I was early enough in my in my project that I did what you're never supposed to do and I deleted everything in the database and all the migrations and started over from scratch. You'd probably want to do a sequence of migrations where you add that field. populate it again doing something very similar here right taking those two distinct fields and applying their value to the new field and then eventually removing that field. There was actually there was a really good talk yesterday about migrations. I'd encourage you to watch that video after this

or whenever it comes up on the Django Con site. For some tips on how to make those sorts of changes. Well thank you all very much. It was a pleasure speaking with you.