Django ORM - a model object from using .get or indexing a QuerySet

my_model = MyModel.objects.get(pk=5)

So 'my_model' is not a queryset object, neither would it be if I indexed it from a queryset. Is there something special about a QuerySet other than it is a list of objects from the table(s)?

Also I was wondering, I know that simply creating a QuerySet does not involve a database lookup, but what about getting just one object like in 'my_model'?

1 answer

  • answered 2018-01-11 21:08 wobbily_col

    A queryset is a "list of objects" in the most basic sense, but it also has a fair number of methods that are not available to a normal list.

    https://docs.djangoproject.com/en/2.0/ref/models/querysets/

    So for example you can filter a queryset further to produce another queryset. You can view the SQL generated by the queryset, you can get aggregates from a queryset.

    I know that simply creating a QuerySet does not involve a database lookup

    Querysets are lazily evaluated. That means they don't hit the database until needed. So in your example "getting one just model" would need to get information from the database.

    Other things that will cause the query to actually lookup the database will be anything that actually needs information that is stored in the database - so iterating over the queryset, rendering a value in a template, calling list(my_queryset) or the count() method. There is a section at the top of the link I posted expalining this.