본문 바로가기

BackEnd/Django

[Django]Notification App 만들기


다음과 같이 나에 변화를 알려주는 알람!을 만들어볼꺼임


django-admin startapp notifications


다음을 통해서 notification app을 만들고


from django.db import models
from Moonstargram.users import models as user_models
from Moonstargram.images import models as image_models

class Notification(image_models.TimeStampedModel) :
TYPE_CHOICES = (
('like', 'Like'),
('comment', 'Comment'),
('follow', 'Follow')
)

creator = models.ForeignKey(user_models.User, on_delete=models.PROTECT, related_name='creator')
to = models.ForeignKey(user_models.User, on_delete=models.PROTECT, related_name='to')
Notification_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
image = models.ForeignKey(image_models.Image, on_delete=models.PROTECT, null=True, blank=True)


모델을 만들었다.


필요한건


내게 변화를 준 유저네임, 팔로우/댓글/좋아요와 같은 타입,이미지 , 몇 일 지났는지


이다.  


Notification이라는 이름이고 image의 TimeStampModel을 참고함(언제 생성됬는지, 언제 업데이트 됬는지)


여기서 몇 일은 해결


그리고 유저네임과 관련된 것들은 이미 User에서 만들었기 떄문에 Foreign키를 적극 활용함!


creator -> 외래키


to -> 외래키


image -> 외래키


image가 필요한 건 누군가가 좋아요를 했다면 그 이미지가 뜰 꺼기 때문.


여기서 눈여겨 볼 점은


related_name은 같은 외래키를 참조하는 creator와 to를 구분하기 위해 작성


Notification_type 속성은 새로 생성했고


좋아요, 코멘트, 튜플로 선택할 수 있게 되어있다.


from django.contrib import admin
from . import models

@admin.register(models.Notification)
class NotificationAdmin(admin.ModelAdmin):

list_display =(
'creator',
'to',
'Notification_type'
)


어드민 창은 다음처럼 되어 있음!


여기서 좋아요 같은 것은 남이 선택해주는것이기 때문에


image와 같은 것은 선택되어지지 않았음