On the difference between django model get and filter of

  • 2020-06-01 10:11:29
  • OfStack

The get and filter methods of django are commonly used by django and model, and it is important to know the difference between them.

To illustrate the difference between the two, define two models


class Student(models.Model):
name = models.CharField(' The name ', max_length=20, default='')
age = models.CharField(' age ', max_length=20, default='')


class Book(models.Model):
student = models.ForeignKey(Student)

1. First, let's talk about the get method of django:

1. The get method of django gets a matching result from the database and returns an object. If the record does not exist, it will report an error.

For example, if I have a record in my database and the value of name is Python of this site, I use student = Student.objects.get (name=' python of this site '),

It returns a record object, which you can view by student. _ dict _ _, which returns a dictionary, {'key':valeus},key is the name of the field, and values is the content of the value.

If I use the get method to query for a record that does not exist in a database, the program will report an error.

For example :student = Student.objects.get (name=' this site '), you can run it yourself.

2. If you use django's get to get the data of the related table, if there are more than 2 data of the key table, an error will be reported.

For example, I have a record in student:


d name age
1 python 24

book Table: 

id student_id
1 1
2 1 

I use


student = Student.objects.get(name='python')
book = Book.objects.get(student)

It also reports errors because the book table has two records that match the student table.

2. django filter again:

1. The filter method of django gets a match result from the database and returns a list of objects. If the record does not exist, it will return [].

For example, if I have a record in my database, and the value of name is python for this site, I use it

student = Student.objects.filter (name=' this site python')

The student it returns is a list of 1 object. You can see that student[0] and get above return the same result as student.

2. If you use get of django to get the data of the relational table, no matter how many records there are in the relational table, no error will be reported.

In addition to django's more powerful model, forms and templates are also powerful.

In addition, I saw from other materials that filter seems to have the function of caching data. The first time I query the database and generate the cache, the next time I call the filter method, I will directly get the cached data, and the get method will directly query the database every time it is executed. I don't know whether this is correct or not.

This is my experience of django 1 snack which I have used for a period of time. I hope it will be helpful for you to know django get and filter!


Related articles: