Django's Get and filter methods are common to Django model, and it's important to understand the difference between the two.
To illustrate the difference between the two, define 2 models
Class Student (models. Model):
Name = models. Charfield (' name ', max_length=20, default= ')
Age = Models. Charfield (' Age ', max_length=20, default= ')
Class book (Models. Model):
Student = models. ForeignKey (Student)
first, let's say the Django Get method:
The Get method of 1django is to get a matching result from the database, return an object, if the record does not exist, it will error.
For example, I have a record in the database, the name of the record value is old King python, I use Student = Student.objects.get (name= ' old King Python '),
The return is a Record object, which you can see through student.__dict__, which returns a dictionary form, {' key ': Valeus},key is the name of the field, and values is the content of the value.
And if I use the Get method to query a database does not exist in the record, the program will error.
For example: Student = Student.objects.get (name= ' Lao Wang '), you can run to see.
2 If you use Django get to get the data of the related table, and the data of the key table is more than 2, it will be error.
For example, my student table has a record:
ID 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 will also error because the Book table has 2 records that match the student table.
two. Say the Django filter again:
The filter method of 1django is the result of getting a match from the database, returning an object list, which returns [] if the record does not exist.
For example, I have a record in the database, the name of the record value is old King python, I use Student = Student.objects.filter (name= ' old King Python ')
The student that it returns is a list of objects that can be seen student[0] and the result of student returned by the above get method is the same.
2 If you use Django get to get the data of the associated table, no matter how many records the association table has, it will not error.
In addition, I see from other sources that filter seems to have the function of caching data, the first time to query the database and generate the cache, the next time you call the filter method, the direct access to the cached data, the Get method each execution is directly querying the database, do not know if this is correct.
It's a bit of a time I've spent with Django, and I want to help you understand Django get and filter!
Some differences between the Django get and the filter method