I see clone() being used extensively in django code
queryset.query.clone()
queryset.clone()
What is it for and should I mimic the behavior in my queryset or manager methods?
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT .
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
The queryset argument allows you to limit for which objects in the model to create a form for. In your case, for which Order s a form should be displayed. An example is given under Changing the queryset in the docs. By default queryset is set to all of the objects in the model, e.g. Order.
As Kevin points out in his answer, the clone()
method is not a documented part of the Django API. However, the all()
method is fully documented, and does what you probably wanted from clone()
.
all()
Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you’ll definitely have a QuerySet to work with.
When a QuerySet is evaluated, it typically caches its results. If the data in the database might have changed since a QuerySet was evaluated, you can get updated results for the same query by calling all() on a previously evaluated QuerySet.
There are two main reasons for clone()
:
It allows chaining. When you chain querysets together (for example, multiple filter()
calls), you want a fresh copy of the queryset each time that you can modify.
It allows you to avoid stale cache results. Since querysets cache their results when they are evaluated, if you want to make sure you hit the database again you need to clone the queryset.
If you know what you're doing you could use it, but note that it isn't a public API. In this interesting Django developers thread the developers talk about whether or not clone()
should be public. They decide against it, in part because:
The biggest problem with public
.clone()
method is that the private._clone()
doesn't do just cloning. There are some cases where cloning also changes how the QuerySet behaves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With