[Django] URL 쿼리스트링

dhkim·2020년 8월 7일

Django

목록 보기
8/10

get을 이용해 DB에 담겨진 데이터들을 쿼리스트링 을 이용해 내보내보자
먼저 이미 만들어진 모델파일이 있다

#photo/models.py
from django.db      import models

from account.models import (
    User,
    Collection
)

class Photo(models.Model):
    user             = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    image            = models.URLField(max_length  = 255)
    location         = models.CharField(max_length = 50)
    downloads        = models.IntegerField(default=0)
    views            = models.IntegerField(default=0)
    hashtag          = models.ManyToManyField('HashTag', through='PhotoHashTag')
    collection       = models.ManyToManyField(Collection, through ='PhotoCollection')
    background_color = models.ForeignKey('BackGroundColor', on_delete = models.SET_NULL, null=True)
    width            = models.IntegerField(null=True)
    height           = models.IntegerField(null=True)
    

    class Meta:
        db_table = 'photos'

class HashTag(models.Model):
    name = models.CharField(max_length = 50)

    class Meta:
        db_table = 'hashtags'

class PhotoHashTag(models.Model):
    photo   = models.ForeignKey(Photo, on_delete = models.SET_NULL, null = True)
    hashtag = models.ForeignKey(HashTag, on_delete = models.SET_NULL, null = True)

    class Meta:
        db_table = 'photos_hashtags'

class PhotoCollection(models.Model):
    photo      = models.ForeignKey(Photo, on_delete = models.SET_NULL, null = True)
    collection = models.ForeignKey(Collection, on_delete = models.SET_NULL, null = True)

    class Meta:
        db_table = 'photos_collections'

class BackGroundColor(models.Model):
    name = models.CharField(max_length=50)

    class Meta:
        db_table = 'background_colors'
#account/models.py

from django.db import models

class User(models.Model):
    first_name    = models.CharField(max_length=50)
    last_name     = models.CharField(max_length=50)
    user_name     = models.CharField(max_length=50)
    email         = models.EmailField(max_length=255)
    password      = models.CharField(max_length=255)
    profile_image = models.URLField(max_length=2000, null=True)
    is_active     = models.BooleanField(default=False)
    created_at    = models.DateTimeField(auto_now_add=True)
    updated_at    = models.DateTimeField(auto_now=True)
    user          = models.ManyToManyField('self', through='Follow')
    interest      = models.ManyToManyField('Interest', through='UserInterest')
 
    class Meta:
        db_table = 'users'

    def __str__(self):
        return self.email

class Like(models.Model):
    user  = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    photo = models.ForeignKey('photo.Photo', on_delete=models.SET_NULL, null=True)

    class Meta:
        db_table = 'likes'

class Interest(models.Model):
    name = models.CharField(max_length=50)

    class Meta:
        db_table = 'interests'

    def __str__(self):
        return self.name

class UserInterest(models.Model):
    user     = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    interest = models.ForeignKey(Interest, on_delete=models.SET_NULL, null=True)

    class Meta:
        db_table = 'users_interests'

class Follow(models.Model):
    from_user = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='from_user')
    to_user   = models.ForeignKey('User', on_delete=models.SET_NULL, null=True, related_name='to_user')
    status    = models.BooleanField(default=True)

    class Meta:
        db_table = 'follows'

class Collection(models.Model):
    user        = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name = 'collection')
    name        = models.CharField(max_length=50, null=False)
    description = models.CharField(max_length=500, null=True)
    private     = models.BooleanField(default=False)

    class Meta:
        db_table = 'collections'

    def __str__(self):
        return self.name

다음 view파일을 작성한다


class BackgraundView(View):
    def get(self,request, collection_name):
        try:
            photos = Photo.objects.filter(
                collection = Collection.objects.get(name=collection_name)
                ).prefetch_related("user","background_color")
            data = [{
                "id" : photo.id,
                "background_color" : photo.background_color.name,
                "width" : photo.width,
                "height" : photo.height
            }for photo in photos]
            return JsonResponse({"data":data},status=200)

        except ValueError:
                return JsonResponse({"message":"VALUE_ERROR"},status=400)
        except KeyError:
            return JsonResponse({"message":"KEY_ERROR"},status=400)

photo의 collection의 background정보를 담은 view를 작성했다

이제 URL을 바꿔주면

from django.urls import path
from .views      import PhotoView, BackgraundView

urlpatterns= [
    path('/back/<collection_name>',BackgraundView.as_view())
]

완성된다

0개의 댓글