2👍
You wouldn’t want to monkeypatch that sucker, because once the Item
type gets created, it’s state is then shared between threads, which includes the default manager. It’s possible then that you retrieve 10 items, even though the user for the current request is of type long
, because you have thread contention on the model manager. (see ModelBase in the package django.db.models.base
)
In your case, you’ll want to make it very obvious what is it that your doing. This is my best guess:
class ItemManager(models.Manager):
def latest_for_user_type(user_type):
limit = user_type=='brief' and 10 or user_type=='long' and 30
return self.get_query_set().order_by('date')[:limit]
class Item(models.Model)
# ...
objects = ItemManager()
# views.py
class LatestItemListView(ListView):
def get_query_set(self):
return Item.objects.latest_for_user_type(
user_type=user_type(self.request.user)
)
You might want to implement the user_type()
logic in ItemManager
… you might even want to refactor it to be latest_for_user(user=None, user_type=None)
. This is just the basic idea and there are other ways, such as proxy classes, that are ideal (the only way true way) for overriding model managers.
Managers are the right way to implement anything that operates on collections.