Python's Django Objects.get and Objects.filter methods

Source: Internet
Author: User

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, the Django Obj.get ():
The Django get gets a match from the database, returns an object, and, if the record doesn't exist, it gets an error.
For example, I have a record in my database, the name value of the record is "Django", I use Student = Student.objects.get (name= ' Django '),
The return is a record object that you can pass through student. Dict to see that it 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= ' python ')

If you use Django get to get the data for the associated table, the data for the key table will be error if more than 2.
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 Django Filter method returns a list of objects from the result of a database match, and returns [] if the record does not exist.
For example, I have a record in the database, the name of the record value is Python, I use Student = Student.objects.filter (name= ' 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.

Python's Django Objects.get and Objects.filter methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.