0

我正在尝试开发一个具有类似于站点框架的操作的模型管理器。根据用户的字段,ModelManager 返回一个查询集。我试图模仿站点框架的操作,但我不明白如何使用此函数动态获取 SITE_ID:

    def get_queryset(self):
    return super(CurrentSiteManager, self).get_queryset().filter(
        **{self._get_field_name() + '__id': settings.SITE_ID})

它似乎是静态的:/。

我通过中间件捕获用户的字段并将其分配给 request.field。如何在 ModelManager 中检索该字段并执行查询?

4

1 回答 1

0

我认为您缺少获取当前站点实例的动态方式。从文档示例中:

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() 查找当前站点。

您应该阅读文档的这一部分,它实际上解释了 django 如何以动态方式获取当前站点:

快捷方式.get_current_site(请求)

检查 django.contrib.sites 是否已安装并根据请求返回当前 Site 对象或 RequestSite 对象的函数。如果未定义 SITE_ID 设置,它将根据 request.get_host() 查找当前站点。

当 Host 标头具有明确指定的端口时,request.get_host() 可能会返回域和端口,例如 example.com:80。在这种情况下,如果由于主机与数据库中的记录不匹配而导致查找失败,则会剥离端口并仅使用域部分重试查找。这不适用于始终使用未修改主机的 RequestSite。

这是实际调用的代码get_currentget_current_site

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."
    )
于 2017-11-16T01:25:32.057 回答