Django Template – with 변수 선언

변수가 너무 길어서 엄청 불편함, 좀 줄인 변수에 넣어서 해보고 싶어서 좀 찾아봄, 예를 들어 request.user.profile.company.name 이런 식의 변수를 간단하게 쓰면 좋겠다 😁

with 구문으로 페이지에 쓰일 사용자 변수를 선언해서 쓸 수 있네.

{% with total=business.employees.count %}	{{ total }} employee{{ total|pluralize }}{% endwith %}

복수 개를 선언 하려면, 한 칸 띄우고 선언을 쭉 하면 된다.

You can assign more than one context variable:

{% with alpha=1 beta=2 %}	... {% endwith %}

참고로, 이전에 with as 구문으로 사용했다고 하네.

😊
The previous more verbose format is still supported: `{% with business.employees.count as total %}`

참고 페이지

장고 사이트에서 with 구문 위치

[
Built-in template tags and filters | Django documentation | Django
![](https://static.djangoproject.com/img/fundraising-heart.cd6bb84ffd33.svg)
](https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#with)

Django ORM – 쿼리셋 합치기

가장 기본적인 것 같은데, 막상 하려면 다 찾아봐야 해

장고 ORM 쿼리셋 2개를 하나로 합치고 싶다면

union() or “ ” 를 이용하면 된다. 자세한 내용은 아래 링크로

result = a.union(b, all=True)

[
[Django] queryset 결과 합치기
합칠 대상의 결과가 2개 이상인 경우 union() union()를 사용해서 1개로 합칠 수 있습니다. union()의 2번째 인자는 중복을 허용할지에 대한 여부인데 기본값은 False로 중복을 허용하지 않습니다. (중복데이터일..
![](assets/images/2023/02/opengraph.png?ssl=1)
](https://brownbears.tistory.com/426)

아니면, 쿼리셋 2개를 OR 하자

queryset = User.objects.filter(first_name__startswith='R') 			|             User.objects.filter(last_name__startswith='D')queryset <QuerySet [<User: Ricky>, <User: Ritesh>, <User: Radha>, <User: Raghu>, <User: rishab>]>

참고 사이트는 여기

[
2. OR 연산으로 일부 조건을 하나라도 만족하는 항목을 구하려면 어떻게 하나요? — Django ORM Cookbook 2.0 documentation
![](assets/images/2023/02/usertable.png?ssl=1)
](https://django-orm-cookbook-ko.readthedocs.io/en/latest/or_query.html)

PostgreSQL – 파이썬으로 select and copy 구현 – executemany()

파이썬 라이브러리 psycopg2 를 이용해서 select 구문으로 읽은 데이터를 insert 구문으로 복사해서 넣는 아주 무식한 동작을 해보자. psql 쿼리로 연속적인 대량의 데이터를 처리하는 경우, 그냥 executemany 를 써서 편리하게 이용했다. 간단한 executemany 예제를 볼까?

executemany 예제

사실 이런 예제는 다른 2개의 database 사이에 데이터를 옮길때나 필요하지 쓸일이 없는 것 같긴한데, 많이 쓰니깐 이런 기능이 있었겠지. 암튼

  1. connection 과 cursor 를 각각 소스와 목적지에 맞게 맞춰두고, 먼저 소스에서 SELECT 구문으로 읽어드린다.
  2. 이때, 원하는 필드를 순서대로 지정하는 것이 좋다. 넣을때 그대로 넣으면 되니깐
  3. fetchall() 기능으로 읽을 결과를 리스트에 저장하고,
  4. 목적지에다가 executemany() 를 통해 일괄 넣어 버린다.
# worktimelog 정보는 아래에 추가for orderitem_id in orderitem_id_list:    postgreSQL_select_Query = """SELECT updated_at, created_at, jigcount, jigmanager_id, orderitem_id FROM testxapi_worktimelog WHERE orderitem_id=%s ORDER BY id ASC"""    cur_dev_db.execute(postgreSQL_select_Query, (orderitem_id,))    mobile_records = cur_dev_db.fetchall()        # 대상 테이블에 추가    sql_insert_query = """ INSERT INTO testxapi_worktimelog (updated_at, created_at, jigcount, jigmanager_id, orderitem_id)    VALUES (%s,%s,%s,%s,%s) RETURNING id"""    result = cur_final_db.executemany(sql_insert_query, mobile_records)    con_final_db.commit()

기초 참고 예제

아래 사이트에서 기본을 배우면 더 쉽게 코드를 이해할 수 있습니다. 위 코드는 아래 사이트에서 예제를 가져다가 수정한 것입니다.

성능개선

아래 링크를 읽고 좀 반성. 1회성 일이라 그냥 해 버렸는데 실시간 활용이 필요한 경우 아래 글을 참고하세요.

[
Psycopg2.extras를 이용한 Bulk Insert: executemany로 성능 절반 손해봤어어! – 인하대학교 인트아이
Python에서는 Psycopg2를 이용해 PostgreSQL DB에 접근할 수 있습니다. 참고: Python과 PostgreSQL 연동 -> Psycopg2 대량의…
![](assets/images/2023/02/thumbnail.jpg?ssl=1)
](https://int-i.github.io/python/2022-02-27/python-postgres-psycopg2-bulk-insert/)