2017-11-16 1 views
0

사이트 프레임 워크와 비슷한 작업으로 ModelManager를 개발하려고합니다. 사용자 필드에 따라 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에서 해당 필드를 검색하고 쿼리를 수행하려면 어떻게해야합니까?

답변

0

현재 사이트 인스턴스를 동적으로 얻지 못하고 있다고 생각합니다. 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()를 기반으로 현재 사이트를 조회합니다.

shortcuts.get_current_site (요청)

django.contrib 경우 검사하는 기능 :

당신은 this part of the documentation 실제로 장고 동적 방식으로 현재 사이트를 얻을 수있는 방법을 설명 읽어야 .sites가 설치되고 요청을 기반으로 현재 Site 객체 또는 RequestSite 객체를 반환합니다. SITE_ID 설정이 정의되지 않은 경우 request.get_host()를 기반으로 현재 사이트를 조회합니다.

호스트 헤더에 포트가 명시 적으로 지정된 경우 request.get_host()에 의해 도메인과 포트가 모두 반환 될 수 있습니다 (예 : example.com:80. 이 경우 호스트가 데이터베이스의 레코드와 일치하지 않기 때문에 조회가 실패하면 포트가 제거되고 조회는 도메인 부분으로 만 재 시도됩니다. 이는 수정되지 않은 호스트를 항상 사용하는 RequestSite에는 적용되지 않습니다. 여기

그리고 실제로 get_current_site에 의해 호출 된 get_currentcode입니다 : 좋아

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." 
    ) 
+0

. 이 함수는 동적입니다. 그러나 그것은 어떻게 CurrentSiteManager를 동적으로 만들었습니까 ??? https://docs.djangoproject.com/en/1.11/ref/contrib/sites/#django.contrib.sites.managers.CurrentSiteManager – paralosreg

+0

질문 제목은 "사이트 프레임 워크의 작동 방식"입니다. 귀하의 질문에 대한 세부 사항에서 "이 함수로 SITE_ID를 동적으로 얻는 방법을 모르겠다"및 "정적 인 것으로 보인다 : /."라고 썼습니다. 나는이 두 가지 질문에 모두 대답한다 ... –

+0

은이 fuction과 함께 동적으로 얻어진다. 이 기능은 CurrentSiteManager에 있습니다. CurrentSiteManager는 항상 정적 SITE_ID var를 반환합니다. – paralosreg

관련 문제