[Django REST API] Program
[REST API Program model]
class Board(models.Model):
title = models.CharField(max_length=500)
description = models.TextField(blank=True, null=True)
content = RichTextUploadingField(blank=True, null=True)
view_count = models.IntegerField(default=0, blank=True)
display_order = models.IntegerField(default=0, blank=True, null=True)
open = models.IntegerField(choices=codes.YESNO, default=0)
popup = models.IntegerField(choices=codes.YESNO, default=0)
status = models.IntegerField(choices=codes.STATUS, default=1)
creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name='board_creator', null=True, blank=True)
modifier = models.ForeignKey(User, on_delete=models.PROTECT, related_name='board_modifier', null=True, blank=True)
created = models.DateTimeField(default=timezone.now)
modified = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
''' On save, update timestamps '''
user = get_current_user()
if not self.id:
self.created = timezone.now()
try:
self.creator = user
except:
self.creator = self.creator
self.modified = timezone.now()
try:
self.modifier = user
except:
self.modifier = self.modifier
return super(Board, self).save(*args, **kwargs)
class BoardAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'display_order', 'open', 'popup', 'status')
readonly_fields = ('creator', 'modifier', 'created', 'modified')
list_filter = ['status', 'open', 'popup']
list_display_links = ['title']
list_per_page = 10
admin.site.register(models.Board, BoardAdmin)
class BoardSerializer(serializers.ModelSerializer):
class Meta:
model = models.Board
fields = '__all__'
views.py
class BoardViewSet(viewsets.ModelViewSet):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
renderer_classes = [JSONRenderer]
queryset = models.Board.objects.all()
serializer_class = serializers.BoardSerializer
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_fields = '__all__'
search_fields = ['title']
ordering_fields = '__all__'
ordering = ['created']
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'boards', views.BoardViewSet, basename='board')
urlpatterns = [
path('', include(router.urls)),
]
댓글
댓글 쓰기