2 python django mongoengine django-rest-framework
为了提高性能,在我的项目中,大多数模型实例都作为列表值存储在缓存中。但 Django Rest Framework 中的所有通用视图都期望它们是查询集对象。如何将从列表中获得的值转换为像对象这样的查询集,以便我可以使用通用视图。
说,我有一个类似的功能
def cache_user_articles(user_id):
key = "articles_{0}".format(user_id)
articles = cache.get(key)
if articles is None:
articles = list(Article.objects.filter(user_id = user_id))
cache.set(key, articles)
return articles
Run Code Online (Sandbox Code Playgroud)
在我看来.py,
class ArticleViewSet(viewsets.ModelViewSet):
...
def get_queryset(self, request, *args, **kwargs):
return cache_user_articles(kwargs.get(user_id))
Run Code Online (Sandbox Code Playgroud)
但是,这当然是行不通的,因为 Django Rest Framework 期望结果是get_querysetQuerySet 对象,并且根据PUT请求它会调用它的“get”方法。有什么办法可以让它与通用 DRF 视图一起使用。
这就是像动态语言这样的 Python 真正大放异彩的地方,因为Duck Typing. 您可以轻松地编写一些像QuerySet.
import mongoengine
from bson import ObjectId
class DuckTypedQuerySet(list):
def __init__(self, data, document):
if not hasattr(data, '__iter__') or isinstance(data, mongoengine.Document):
raise TypeError("DuckTypedQuerySet requires iterable data")
super(DuckTypedQuerySet, self).__init__(data)
self._document = document
@property
def objects(self):
return self
def _query_match(self, instance, **kwargs):
is_match = True
for key, value in kwargs.items():
attribute = getattr(instance, key, None)
if isinstance(attribute, ObjectId) and not isinstance(value, ObjectId):
attribute = str(attribute)
if not attribute == value:
is_match = False
break
return is_match
def filter(self, **kwargs):
data = filter(lambda instance: self._query_match(instance, **kwargs), self)
return self.__class__(data, self._document)
def get(self, **kwargs):
results = self.filter(**kwargs)
if len(results) > 1:
raise self._document.MultipleObjectsReturned("{0} items returned, instead of 1".format(len(results)))
if len(results) < 1:
raise self._document.DoesNotExist("{0} matching query does not exist.".format(str(self._document)))
return results[0]
def first(self):
return next(iter(self), None)
def all(self):
return self
def count(self):
return len(self)
def cache_user_articles(user_id):
key = "articles_{0}".format(user_id)
articles = cache.get(key)
if articles is None:
articles = DuckTypedQuerySet(list(Article.objects.filter(user_id = user_id)), document = Article)
cache.set(key, articles)
return articles
Run Code Online (Sandbox Code Playgroud)
当然,这并不是一个详尽的实现。您可能需要添加查询集中存在的其他方法。但我认为这些适用于简单的用例。现在您可以使用 Django Rest Framework 的通用实现。
| 归档时间: |
|
| 查看次数: |
3993 次 |
| 最近记录: |