我正在尝试开发一个类似于站点框架的操作的ModelManager。根据用户的字段,ModelManager返回一个查询集。我试图模仿Sites Framework的操作,但我不明白如何使用此函数动态获取SITE_ID:
def get_queryset(self):
return super(CurrentSiteManager, self).get_queryset().filter(
**{self._get_field_name() + '__id': settings.SITE_ID})它似乎是静态的:/。
我通过中间件捕获用户的字段,并将其分配给request.field。如何检索ModelManager中字段并执行查询?
发布于 2017-11-16 09:25:32
我认为你错过了获取当前站点实例的动态方法。在documentation示例中:
from django.contrib.sites.shortcuts import get_current_site
def article_detail(request, article_id):
try:
a = Article.objects.get(id=article_id,
sites__id=get_current_site(request).id)
except Article.DoesNotExist:
raise Http404("Article does not exist on this site")
# ...您应该使用get_current_site方法来获取当前站点。
需要注意的是,如果你真的在SITE_ID=1这样的设置中定义了当前站点,那么它就不起作用了。
如果未定义SITE_ID设置,则
将根据request.get_host()查找当前站点。
你应该阅读this part of the documentation,它解释了django如何以动态的方式获取当前站点:
shortcuts.get_current_site(request)
检查是否安装了django.contrib.sites并根据请求返回当前Site对象或RequestSite对象的函数。如果未定义SITE_ID设置,它将基于request.get_host()查找当前站点。
当主机标头具有显式指定的端口时,request.get_host()可以同时返回域和端口。在这种情况下,如果由于主机与数据库中的记录不匹配而导致查找失败,则端口将被剥离,并且仅使用域部分重试查找。这不适用于始终使用未修改主机的RequestSite。
这是get_current_site实际调用的get_current的code
def get_current(self, request=None):
"""
Return the current Site based on the SITE_ID in the project's settings.
If SITE_ID isn't defined, return the site with domain matching
request.get_host(). The ``Site`` object is cached the first time it's
retrieved from the database.
"""
from django.conf import settings
if getattr(settings, 'SITE_ID', ''):
site_id = settings.SITE_ID
return self._get_site_by_id(site_id)
elif request:
return self._get_site_by_request(request)
raise ImproperlyConfigured(
"You're using the Django \"sites framework\" without having "
"set the SITE_ID setting. Create a site in your database and "
"set the SITE_ID setting or pass a request to "
"Site.objects.get_current() to fix this error."
)https://stackoverflow.com/questions/47319637
复制相似问题