Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
The `.filter()` method let's us filter things down by more than just relations. Let's explore these other lookups and how to use the `.exclude()` method.
More on filter()
and exclude()
.
Model.objects.filter(attribute__condition=value)
The conditions are called field lookups and there are a lot of them. The ones I seem to use the most often are gte
(greater than or equal to), lte
(less than or equal to), in
(uh, just like Python's in
keyword), and icontains
(case-insensitive in
for strings). I'm sure you'll find some that you love, too.
The condition can also be a related model, so, for example, if C
has a foreign key to B
and B
has a foreign key to A
, you could do: C.objects.filter(b__a__id__in=[1, 5, 10])
to get all of the C
objects that have a B
object with an A
object whose id
attribute is 1, 5, or 10. Yes, this is an over-engineered, overly-complicated scenario, but you'll be surprised how often similar things come up.
If you're coding along and the form isn't submitting when you click the button, change the button's type
attribute to be "submit"
(or, better yet, turn it into <input type="submit">
with all of the other classes applied).
You need to sign up for Treehouse in order to download course files.
Sign up