이번 프로젝트를 마치며

코변·2022년 7월 6일
0

개발일지

목록 보기
39/41

앞으로 프로젝트를 할 때 쓰면 좋을 작은 코드 조각들

  1. drf - serializer의 context를 통해서 request데이터 넘겨주어 처리하기
# post 시리얼라이저에서 context를 선언하고 그 안에 request를 담아준다.
"posts": PostSerializer(posts, many=True, context={'request' : request}).data,
# 시리얼라이저 안쪽에서 북마크를 했는지 여부를 아래와 같은 코드로 나타낼 수 있음
def get_bookmarked(self, obj):
        cur_user = self.context['request'].user
        return SavePostModel.objects.filter(save_post =obj, save_user = cur_user).exists()

이전 프로젝트에서 일일히 작성자와 유저가 같은지 검사하여 True False의 리스트로 반환했던 지옥같던 코드를 생각하면 엄청나게 직관적이고 간단하게 나타낼 수 있었다.

  1. |= 연산을 통해 쿼리셋과 쿼리셋 더하기
recommend_followers = UserModel.objects.none()
for user_obj in my_followers:
	recommend_followers|= user_obj.follow.all()
	recommend_followers.exclude(id__in = my_followers).exclude(id=cur_user.id).order_by('-created_date')[:10]
    if len(recommend_followers) == 0:
    	recommend_followers = UserModel.objects.all().exclude(
        id__in = my_followers).exclude(id=cur_user.id).order_by('-created_date')[:10]

효율적인 코드라고 할 수는 없지만 위와 같이 동일한 오브젝트에 대한 union을 실행할 때 간단하게 사용하기 좋아보인다. 참조한 스택오버플로우에서도 권장되는 사항은 아니라고 한다. 내 생각에는 쿼리셋간의 모든 값 그러니까 아우터 조인 같은 역할을 하게 되는 것 같은데 그러면 내가 제어할 값들이 감당할 수 없을정도로 많아질 수도 있고 필요한 데이터를 가져오기보다는 데이터가 무작정 쌓이기만 할 것 같아서 인 것 같다.
출처 : https://stackoverflow.com/questions/29587382/how-to-add-an-model-instance-to-a-django-queryset

  1. 프론트 부분 들어오는 query params에 따라 페이지 전환
const urlParams = new URLSearchParams(window.location.search);
const post_type = urlParams.get('page_type');

if (post_type === 'liked'){
    URL = BASE_URL + '/test/likedpage/' 
}else if (post_type === "saved"){
    URL = BASE_URL + "/test/bookmark/"
}else{
    URL = BASE_URL + '/test/mypage/'
}
const myimg_list = document.querySelector('.myimg_list');

window.onload = async function(){
    if (!localStorage.hasOwnProperty('access')) {
        location.replace('/user/sign_page.html')
    }

    token = localStorage.getItem('access');
    const myposts = await fetch(URL,{
        method:'GET',
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Authorization": `Bearer ${token}`,
        }
    })
    let response = await myposts.json()

동료의 코드를 가져왔다. switch 구문으로 더 많은 값들을 제어할 수도 있을 것 같다. 간단하게 프론트에서 보내주는 query params값으로 백엔드에 보내는 url을 바꿔주어 페이지 전환을 시켰다. 코드를 좀 더 다듬으면 앞으로 같은 페이지 내에서 가져오는 데이터만 달라질 경우 잘 활용할 수 있을 것으로 보인다.

  1. page_num이라는 값으로 페이지를 제어하여 일정한 수만큼만 데이터를 가져오는 로직
async function get_other_posts() {
    if (parseInt(len_of_posts / 4) >= page_num && ((mb_left.scrollTop + mb_left.offsetHeight) >= (mb_left.scrollHeight))) {
        const loading = document.querySelector('.loading');
        loading.style.display = 'block';
        setTimeout(async () => {
            loading.style.display = 'none';
            token = localStorage.getItem('access');
            const result = await fetch(BASE_URL + '/test/?page_num=' + page_num, {
                method: 'GET',
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    "Authorization": `Bearer ${token}`,
                },
            })
            let response = await result.json()
            if (result.status == 200) {
                page_num += 1
 page_num = int(self.request.query_params.get('page_num'))
 posts = post_models[page_num *4 : (page_num+1) *4]

이 함수에서는 4개씩 데이터를 가져와 화면에 보내주는 코드들의 조각이다. setTimout을 통해서 중복되는 데이터요청을 방지하고 로딩창을 띄워준다. 너무 많은 데이터를 한 번에 페이지에 넣으면 페이지를 이용하기에도 불편하고 페이지를 무겁게 만드는 요인이 된다. 앞으로 프로젝트를 진행하면서 사용할 일이 있을 것으로 보임

profile
내 것인 줄 알았으나 받은 모든 것이 선물이었다.

0개의 댓글