What is query.clone (), queryset.clone () for django?

I see that clone () is widely used in django code

queryset.query.clone() queryset.clone() 

Why am I and should I mimic behavior in request methods or manager?

+6
source share
2 answers

There are two main reasons for clone() :

  • This allows the chain. When you chain ask each other (for example, several filter() calls), you need a new copy of the query set every time you can change.

  • This avoids stale cache results. Since querysets cache their results when evaluating them, if you want you to get into the database again, you need to clone the request.

If you know what you are doing, you can use it, but note that this is not a public API. In this interesting Django thread developer, the developers talk about whether clone() should be open. They solve this, in part because:

The biggest problem with the public .clone() method is that private ._clone() doesn't just clone. In some cases, cloning also changes the behavior of the QuerySet.

+9
source

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() .

everything()

Returns a copy of the current QuerySet (or subclass of QuerySet). This can be useful in situations where you might want to go through either the model manager or QuerySet and continue filtering the result. After calling all () on any object, you will definitely have a QuerySet to work with.

When a QuerySet is computed, it usually caches its results. If the data in the database could have changed since the QuerySet was evaluated, you can get updated results for the same query by calling all () for the previously evaluated QuerySet.

+9
source

All Articles