110👍
The Django QuerySet docs are very clear on this:
get(**kwargs)¶
Returns the object matching the given
lookup parameters, which should be in
the format described in Field lookups.get() raises MultipleObjectsReturned
if more than one object was found. The
MultipleObjectsReturned exception is
an attribute of the model class.get() raises a DoesNotExist exception
if an object wasn’t found for the
given parameters. This exception is
also an attribute of the model class.
filter(**kwargs)
Returns a new QuerySet containing objects that match the given lookup parameters.
Basically use get()
when you want to get a single unique object, and filter()
when you want to get all objects that match your lookup parameters.
15👍
Note that behind the scenes the django get() method runs the filter() method, but checks that the filter results set is exactly one record
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
- [Django]-How do I use Django groups and permissions?
- [Django]-Django logging of custom management commands
11👍
Also, on a side note, assuming pol is not available:
if mymodel=model.objects.get(name='pol').exists()==False:
print "Pol does not exist"
you will get:
AttributeError: ‘Model’ object has no attribute ‘exists’
but:
if mymodel=model.objects.filter(name='pol').exists()==False:
print "Pol does not exist"
you will get: Pol does not exist.
I.e. If you want to run some code depending on whether a single object can be found, use filter. For some reason exists() works on QuerySet but not the specific object returned with get.
- [Django]-Django modifying the request object
- [Django]-Adding model-wide help text to a django model's admin form
- [Django]-How to run this code in django template
6👍
get() returns an object that matches lookup criterion.
filter() returns a QuerySet that matche lookup criterion.
For example, the following
Entry.objects.filter(pub_date__year=2006)
is equivalent to
Entry.objects.all().filter(pub_date__year=2006)
which means filter() is slightly expensive operation if the model class has a large number of objects, whereas get() is direct approach.
source: Django making queries
- [Django]-Get current user in Model Serializer
- [Django]-Django Model – Get distinct value list
- [Django]-Django – "no module named django.core.management"
4👍
Another difference:
Because ‘get’ returns an object, the method ‘update’ cannot be called on the object; except a model method (which shouldn’t be done, to avoid overriding), was written.
However, querying with ‘filter’, gives you the ability to update a preferred record.
e.g: say a model; ‘Product’ exists in your app; then you could do thus:
old_product_name = Product.objects.filter(product_name="green-peas")
old_product_name.update(product_name="skewed-peas")
That of course, isn’t possible when you query with ‘get’.
- [Django]-How to create Password Field in Model Django
- [Django]-Why is __init__ module in django project loaded twice
- [Django]-Django REST Framework serializer field required=false
1👍
Django’s get and filter methods are commonly used by django models, and are distinguished here.
Define 2 models.
class Student(models.Model):
Name = models.CharField('name', max_length=15, default='')
Age = models.CharField('age', max_length=15, default='')
class Book(models.Model):
student = models.ForeignKey(Student)
A.django get method:
-
django’s get method is to get a matching result from the database, return an object, if the record does not exist, it will report an error. For example, if there is a record in my database, the value of the record name is django123, I use student = Student . objects . get ( name = ’ django123 ’ ),
returns a record object, which you can view through student . _ _ dict _ _, which returns a dictionary form, {‘ key ‘ : valeus}, key is the field The name, while values are the contents of the value.
Using the get method to query a record that does not exist in the database, the program will report an error.
For example: student = Student . objects . get ( name = ’ django ’ ), obviously this ‘django ‘ does not exist in the database, it will report an error. -
If you use django’s get to get the data of the associated table, if the data of the key table is more than 2, it will report an error.
If there is a record in the student table:
d name age 1 python 24 Book table: id student_id 1 1 2 1
student = Student.objects.get(name=’python’)
book = Book.objects.get(student)
The result will be reported because the book table has 2 records that match the student table.
Two.django filter method:
-
django’s filter method is to get a matching result from the database, return a list of objects, if the record does not exist, it will return [ ].
If the database has a record, the value of the record name is python123, using student = Student . objects .filter ( name = ’ python123 ’ ). Returning student is a list of objects. It can be seen that student [ 0 ] is the same as the student returned by the get method above. -
If you use django’s get to get the data of the associated table, no matter how many records in the associated table, no error will be reported.
django In addition to the powerful model, forms and templates are also very powerful.
filter has the function of caching data. The first time you query the database and generate the cache, the next time you call the filter method, you can directly get the cached data, and the get method is directly queried every time in database.
- [Django]-Django ModelForm for Many-to-Many fields
- [Django]-Difference between reverse() and reverse_lazy() in Django
- [Django]-Django delete superuser
1👍
mymodel=model.objects.get(name='pol')
# OR
mymodel=model.objects.filter(name='pol')
Case 1: Suppose we have only one record that matches the name field pol.
- get() will return on single objects whereas filter() will also return a single object in the list.
Case 2: Suppose we have more than one records that match the name field pol.
- get() will raise MultipleObjectsReturned but in the case of filter(), it will return a list of objects.
Case 3: Suppose we have no record found that matches the name field pol.
- get() raises a DoesNotExist exception but in the case of filter(), it will return an empty list.
- [Django]-SocketException: OS Error: Connection refused, errno = 111 in flutter using django backend
- [Django]-How to redirect to previous page in Django after POST request
- [Django]-'RelatedManager' object has no attribute
0👍
if you know it’s one object that matches your query, use “get”. It will fail if it’s more than one and gives the error like this
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 143, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 407, in get
(self.model._meta.object_name, num))
MultipleObjectsReturned: get() returned more than one Poll -- it returned 2!
Otherwise use “filter”, which gives you a list of objects.
- [Django]-Running django tutorial tests fail – No module named polls.tests
- [Django]-Django class-based view: How do I pass additional parameters to the as_view method?
- [Django]-Rendering JSON objects using a Django template after an Ajax call
-3👍
Model = Employee
Employee : name,age,loc
Get:
Employee.objects.get(id=1)
It will through error if given object is not there
Filter :
Employee.objects.filter(id=1)
]>
It will return empty Queryset if given object is not there
- [Django]-Annotate with latest related object in Django
- [Django]-How to use "get_or_create()" in Django?
- [Django]-Change a form value before validation in Django form