QuerySet
A QuerySet represents a collection of objects from your database.
- objects are model's manager.
- QuerySet is a List!!! So you need an index.
- Or, instead of an index, you can put first() in order to get an object.
Methods that return new QuerySets
filter()
- Returns a new QuerySet containing objects that **match the given lookup parameters.**
- **Q objects**: When you use more complex queries (queries with OR statements)
values()
- Returns a QuerySet that returns dictionaries, rather than model instances. (It does return a Queryset, but more detailed one).
Methods that do not return new QuerySets
get() returns the object matching the given lookup parameters.
- As you can see, it doesn't return a queryset.
- Rather, It returns an object(<>).
- get() mehtod can only return one object. Otherwise, it'll raise MultipleObjectsReturned.
Difference between get() and filter()
Using django ORM to our project model
In order to get to the name of the category of the subcategory of the product, we do so like this:
Product.objects.values("sub_category__category__name")
- Within a class, when you wabt to go to another class linked with a Foreignkey, you need to do TWO UNDERSCORES.
YOU CAN'T DO THIS:
Product.objects.values("sub_category.category.name")
- When you're referencing the opposite way, you can do
_set
or related_name
.
select_realted() & prefetch_realted() calls all the data we need in advance, so it hits the DB only once. Queries might get complicated, but the data remains in the cache, so we don't have to hit DB every time we call this data. In addition, when we call different attributes (like name, hashtag, image_url), we use period(.).