2023. 5. 1. 12:29ㆍdjango/Views
Django에서 모델에 새로운 데이터를 추가하고 데이터베이스에 저장하는 방법은 크게 두 가지가 있습니다.
- save() 메서드를 사용하는 방법
from myapp.models import MyModel
# MyModel 객체 생성
new_obj = MyModel(field1='value1', field2='value2', ...)
# 객체 저장
new_obj.save()
- create() 메서드를 사용하는 방법
from myapp.models import MyModel
# 객체 생성과 동시에 저장
MyModel.objects.create(field1='value1', field2='value2', ...)
각 필드에 대응하는 값을 전달하면 됩니다. 예를 들어 MyModel이라는 모델에서 title, content, author 필드가 있다면, 다음과 같이 객체를 생성하고 저장할 수 있습니다.
from myapp.models import MyModel
# MyModel 객체 생성
new_obj = MyModel(title='제목', content='내용', author='홍길동')
# 객체 저장
new_obj.save()
또는 create() 메서드를 사용하여 다음과 같이 작성할 수도 있습니다.
from myapp.models import MyModel
# 객체 생성과 동시에 저장
MyModel.objects.create(title='제목', content='내용', author='홍길동')
위 코드는 새로운 MyModel 객체를 생성하고 title, content, author 필드에 각각 '제목', '내용', '홍길동' 값을 저장합니다. save() 메서드는 객체를 생성한 후에도 필드 값을 변경할 수 있지만, create() 메서드는 객체 생성과 동시에 필드 값을 지정하여 저장합니다.
위 코드에서 myapp은 애플리케이션 이름, MyModel은 해당 애플리케이션의 모델 이름입니다. 적절하게 변경하여 사용하시면 됩니다.
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='+') 경우 create에서는 어떻게 적용을 해야 하나요
author 필드가 ForeignKey로 설정되어 있고, User 모델과 연결되어 있다면, 해당 필드에 User 모델의 인스턴스를 할당하여 새로운 데이터를 생성할 수 있습니다.
예를 들어, MyModel 모델에 author 필드가 ForeignKey로 설정되어 있다면 다음과 같이 작성할 수 있습니다.
from django.contrib.auth.models import User
from myapp.models import MyModel
# author에 해당하는 User 객체 가져오기
author = User.objects.get(username='username')
# MyModel 객체 생성
new_obj = MyModel(title='제목', content='내용', author=author)
# 객체 저장
new_obj.save()
위 코드는 MyModel 객체를 생성하고, author 필드에 해당하는 User 객체를 할당하여 데이터베이스에 저장합니다.
author = User.objects.get(username='username') 하지 않고 id를 알고 있는 경우 해당 id를 넣어도 되나요
네, author 필드가 ForeignKey로 설정되어 있으므로, User 모델의 인스턴스 대신 User 모델의 id 값을 할당하여도 새로운 데이터를 생성할 수 있습니다.
예를 들어, User 모델에서 id가 1인 사용자의 객체를 author 필드에 할당하여 새로운 데이터를 생성하려면 다음과 같이 작성할 수 있습니다.
from myapp.models import MyModel
# MyModel 객체 생성 (author에 해당하는 User id를 넣어줌)
new_obj = MyModel.objects.create(title='제목', content='내용', author_id=1)
# 객체 저장
new_obj.save()
위 코드에서 MyModel 객체를 생성할 때, author_id 필드에 해당하는 User 객체의 id 값을 할당하여 데이터를 생성합니다. 이후 save() 메서드를 호출하여 데이터베이스에 저장합니다.
'django > Views' 카테고리의 다른 글
UserCreationForm 상속관점에서 (0) | 2023.05.03 |
---|---|
form.cleaned_data.get('relationship') 검색을 할때 (0) | 2023.05.01 |
request (0) | 2023.04.29 |
django에서 html의 {% form. 종류는 (0) | 2023.04.23 |
category의 title이 'D01' 인것을 Article에서 찾아서 paginator을 이용해서 def article_list(request, subtitle):에 정의 (0) | 2023.04.17 |