웹 프로그래밍

[pinterest clone (34)]Field Lookup을 사용한 구독 페이지 구현

728x90
반응형

지금까지 이렇게 구현을 많이 했었다.

Model.objects.filter(pk=xxx,user=xxx)

조건(pk=xxx,user=xxx)을 잘 보면 이건 AND Function 이다. 그렇다면 OR Function은 어떻게 해야할까?

SQL에서 WHERE 같은 구문은 어떻게 써야할까?

 

 

TODO:

1. 유저가 구독하고 있는 프로젝트들을 확인하는 것

2. 프로젝트들 안에 있는 모든 게시글(articles)들을 가져오는 것


항상 쓰던 식이 이런 식이었는데

Articles.objects.filter(pk=xxx,user=xxx)

이런식으로 바꿀거다. (Field Lookups)

Articles.objects.filter(project__in=projeccts)

 

<Field Lookup> : 좀 더 복잡한 db쿼리를 사용자가 장고에서 쓸 수 있도록 만든것

...(project__in=...) 이거랑 아래 쿼리는 대칭이다.

SELECT ... WHERE project IN (...);

https://docs.djangoproject.com/en/3.1/ref/models/querysets/#field-lookups

 

QuerySet API reference | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com


subscribeapp/views.py

@method_decorator(login_required, 'get')
class SubscriptionListView(ListView):
    model = Article
    context_object_name = 'article_list'
    template_name = 'subscribeapp/list.html'
    paginate_by = 5

    def get_queryset(self):
        projects = Subscription.objects.filter(user=self.request.user).values_list('project')
        article_list = Article.objects.filter(project__in=projects)
        return article_list

get_queryset을 커스텀했다.

 

2

templates/subscribeapp/list.html

{% extends 'base.html '%}

{% block content %}

<div>
    {% include 'snippets/list_fragment.html' with article_list=article_list %}
</div>

{% endblock%}

3

urls.py

from django.urls import path

from subscribeapp.views import SubscriptionView, SubscriptionListView

app_name = 'subscribeapp'

urlpatterns = [
    path('subscribe/', SubscriptionView.as_view(), name='subscribe'),
    path('list/', SubscriptionListView.as_view(), name='list'),
]

 

728x90
반응형