Skip to content

Instantly share code, notes, and snippets.

@prodeveloper
Last active June 25, 2017 12:20
Show Gist options
  • Save prodeveloper/bd7f759d42c77ae33205562adf189832 to your computer and use it in GitHub Desktop.
Save prodeveloper/bd7f759d42c77ae33205562adf189832 to your computer and use it in GitHub Desktop.
Introduction to queries with Django models

Now that we have a solid understanding of what it takes to work with templates, lets dive back to our models and tie them to our views.

Step 1

Ensure that you have imported the Student model into your view file.

Let us now start by querying all students. Type the following command into your view file

Run the project and see what shows up.

You should see a list of the students but only as the infamous Student Object

The query returned a list that had all the students as a list.

Let us now try to pick one.

On the browser you should now only see one Student Object.

Let’s now show one attribute of the student. Say the name.

This can now be seen on the browser as

You can of course show any other attribute by replacing the names attribute with what you are interested e.g. description

Step 2

In the previous step, we were able to get information but not in a granular manner. On a lot of occasions, all you really need is just one value.

Thankfully, django appends a unique identification number for each record in your database. It is an auto increment number that starts from 1 incrementing by 1 for each record.

You can use the method get to fetch any record you want.

Try the following:

The get method can be used with other fields as well, the only caveat is the query must return one and only one result.

Step 3

Fetching a single value is a useful and common use case. We do however from time to time have to fetch a set of information.

An example would be the students that are interested in say python. For this kind of problem, we use the method filter.

We would do this by running the query as follows:

Alternatively we may want the opposite. that is the students who are NOT interested in python. In this case we use the method exclude

At this point in time, the only validation you will get that your code worked is more of the Student object. The curious learner can take on as an exercise how to unpack this information to show it all.

Assignment

When I hit the /students end point in your application. I want to see the name of the student with id 2 in the format that follows: List the name of the 2 nd student in your application in this format.

The student [name] is currently studying [course]

For example

The student Jane Doe is currently studying Python

Tip: Use format method

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment