Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between GET and FILTER in Django model layer

Tags:

What is the difference, please explain them in laymen's terms with examples. Thanks!

like image 970
TIMEX Avatar asked Oct 09 '09 00:10

TIMEX


People also ask

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is get method in Django?

GET is an HTTP method in Django that encapsulates the data in a string and utilizes it to construct a URL. The URL includes the data keys and values as well as the address to which the data must be transmitted.

What is __ exact in Django?

The exact lookup is used to get records with a specified value. The exact lookup is case sensitive. For a case insensitive search, use the iexact lookup.

What does filter return in Django?

Django provides a filter() method which returns a subset of data. It accepts field names as keyword arguments and returns a QuerySet object. As database has only one record where name is 'tom' , the QuerySet object contains only a single record.


1 Answers

I don't know if you really need an example, it's quite easy:

  • if you know it's one object that matches your query, use get. It will fail if it's more than one.
  • otherwise use filter, which gives you a list of objects.

To be more precise:

  • MyTable.objects.get(id=x).whatever gives you the whatever property of your object.

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.

  • MyTable.objects.filter(somecolumn=x) is not only usable as a list, but you can also query it again, something like MyTable.objects.filter(somecolumn=x).order_by('date').
  • The reason is that it's not actually a list, but a query object. You can iterate through it like through a list: for obj in MyTable.objects.filter(somecolumn=x)
like image 137
Jörg Haubrichs Avatar answered Sep 19 '22 21:09

Jörg Haubrichs