Framework/DJANGO
Django / 모두 성공하거나 모두 실패로 처리하기 - transaction.atomic()
YUYA
2021. 3. 21. 16:25
학습 강의
https://www.youtube.com/watch?v=Ij1MCRk-d6c&list=PL9tgJISrBWc5619CclyqYrnnMkVOPzVYM
코드
@login_required
def follow(request, username, option):
#option : follow / unfollow
following = get_object_or_404(User, username=username)
try:
f, created = Follow.objects.get_or_create(follower=request.user, following=following)
#unfollow
if int(option) == 0:
f.delete()
Stream.objects.filter(following=following, user=request.user).all().delete()
else:
posts = Post.objects.all().filter(user=following)[:25]
with transaction.atomic():
for post in posts:
stream = Stream(post=post, user=request.user, date=post.posted, following=following)
stream.save()
return HttpResponseRedirect(reverse('profile', args=[username]))
except User.DoesNotExist:
return HttpResponseRedirect(reverse('profile', args=[username]))
- 트랜잭션 : 하나의 실행 단위로, 존재하는 중간 과정들에 대해서 모두 성공하면 데이터베이스의 상태가 변하게 되고, 중간에 실패하면 기존에 작업들 모두 Rollback
- 원자성
- 모두 성공하거나 모두 실패 둘 중 하나
- 로그인 유저가 팔로잉 하는 유저의 포스트가 모두 보이거나 모두 보이지 않게 만듦
참고