장고 공식문서
django 공식 문서를 참고하여 작성 하였습니다.
b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
b.save()
모델 클래스의 키워드들을 인서턴스화 한 후에 .save() 메소드를 이용해 데이터베이스에 저장한다
이때 생성과 저장을 동시에 하려면
Blog.object.create(name='Beatles Blog' ... )
와 같은 방식을 사용 할 수 있다.
위에서 만든 b 객체의 이름을 변경하려면
b = Blog.object.get(pk = 1)
b.name = 'wwan13 blog'
b.save
위와 같이 수정 할 블로그의 객체를 불러와
불러온 객체의 필드값을 직접 수정 하고 .sava() 메소드를 호출하는 것으로 한다.
ForeignKey 에 내용을 저장하려면 외래키에 해당하는 필드에 직접 저장할 객체를 대입해 주는 방식으로 저장한다.
entry = Entry.object.get(pk = 1)
cheese_blog = Blog.objects.get(name="Cheddar Talk")
# 블로그 객체를 새로 만들 경우
# cheese_blog = Blog.object.create(name="Cheddar Talk")
# entry의 블로그 필드에 불러온 치즈 블로그 객체를 대입 한다.
entry.blog = cheese_blog
entry.save()
manytomanyfield 의 경우 foreignkey와 달리 .add() 메소드를 사용한다.
joe = Author.objects.create(name="Joe")
entry.authors.add(joe)
entry.save()
위와 같이 entry 객체의 manytomanyfield 인 author 에 .add(joe) 를 호출하여 joe 를 entry의 manytomanyfiled에 추가한다.
all_entries = Entry.objects.all()
some_entries1 = Entry.objects.filter(필터링 조건)
some_entries2 = Entry.objects.filter(조건).exclude(조건).filter(조건)
sorted_entries = Entry.objects.order_by('headline')
some_entry = Entry.objects.get(pk = 1)
Blog.objects.get(name__iexact="beatles blog")
- BeaTlES Blog, beaTLES BLOG 등이 결과가 될 수 있음
Entry.objects.get(headline__contains='Lennon')
- search구현 할때 유용하게 사용 될 것 같다.
- Lennon Title, My name is Lennon 등이 결과가 될 수 있음
Entry.objects.filter(blog__name='Beatles Blog')
Blog.objects.filter(entry__headline == 'Lennon')
Blog.objects.filter(entry__headline__contains='Lennon')
Blog.objects.filter(entry__authors__name='Lennon')
Blog.objects.filter(entry__authors__name__isnull=True)
Blog.objects.filter(
entry__authors__isnull=False,
entry__authors__name__isnull=True
)
위와 같은 방법으로도 사용 가능 하다.
대다나시네요!