/images/jg_02.jpg

Django_07_1:N 불러오기

Django 1:N 불러오기

prefetch_related() or annotate()

models.py 구성

1
2
3
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
1
2
3
4
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices')
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# views.py
def get_context_data():
    context["questions"]  = Question.objects.prefetch_related('choices')
    return context

# templates/.html
{% for question in questions %}
    <b>{{ question.question_text }}</b>
    <ul>
        {% for choice in question.choices.all %}
            <li>{{ choice.choice_text }}</li>
        {% endfor %}
    </ul>
{% endfor %}

# Choice 모델에서 related_name을 지정하지 않았을 경우에는 템플릿 쪽에서 question.choice_set.all 을 사용하면 된다.

Django_06_Django & Oracle18 error LOG

Django & Oracle 18 오류 일지

각종 스트레스의 원인에 대하여 해결방법을 정리합니다.

  1. ORA-00955: name is already used by an existing object

    1
    2
    3
    
    # 해결법
    python manage.py makemigrations
    python manage.py migrate --fake-initial
    

    이미 migrate 한 내용을 수정하니 반영되지 않아 오류가 발생하였는데 위의 명령어는 migratie를 초기화해서 재설정 하는 것 같습니다.

Django_05_Check DB connection

Django DB 연결 확인

python manage.py createsuperuser 후.. default로 생기는 DB를 기준으로 실행

1
2
## setting.py
AUTH_USER_MODEL = 'auth.User'   # default 설정.

이후 terminal에서

1
2
3
4
5
6
7
$ python manage.py shell_plus	# 모델에 접근하기 위해 shell_plus 실행

> Post = get_user_model()		# 생성된 모델의 user table 불러오기
> post = Post.objects.all()		# user table의 모든 값 가져오기

> for i in post:				# for문으로 user table값 순환
>     print(i)					# user table 값 출력

하면 연결된 모델의 값을 확인할 수 있다.