https://teamsparta.notion.site/0623-a406cf60e9db40698aace5699f65ba2c
# item/serializers.py
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ['name']
# item/serializers.py
class ItemSerializer(serializers.ModelSerializer):
category = CategorySerializer()
# category = serializers.SerializerMethodField()
# def get_category(self, obj):
# return obj.category.name
class Meta:
model = Item
fields = ['name', 'category', 'image_url']
# item/serializers.py
class OrderSerializer(serializers.ModelSerializer):
item = ItemSerializer(many=True)
class Meta:
model = Order
fields = ['delivery_address', 'order_date', 'item']
# item/serializers.py
class ItemOrderSerializer(serializers.ModelSerializer):
order = OrderSerializer()
item = ItemSerializer()
class Meta:
model = Order
fields = ['order', 'item', 'item_count']
# item/veiws.py
# Item 기능
class ItemView(APIView):
# Item 조회 기능
def get(self, request):
category_name = request.GET['category']
category_object = Category.objects.get(name=category_name)
items = Item.objects.filter(category=category_object)
response = ItemSerializer(items, many=True)
return Response(response.data)
request body는 아래와같이 입력받아서 item을 등록할 것
{ "name":"item3", "category": { "id":1, "name": "food" }, "image_url": "https://www.image.com/" }
# item/serializers.py
class ItemSerializer(serializers.ModelSerializer):
category = CategorySerializer()
# category = serializers.SerializerMethodField()
# def get_category(self, obj):
# return obj.category.name
class Meta:
model = Item
fields = ['name', 'category', 'image_url']
def create(self, validated_data):
# validated_data = {'name' : 'cheese pizza',
# 'category' : {'name': 'pizza'}, ...}
category_data = validated_data.pop('category') # {'name' : 'pizza'}
category_name = category_data.get('name') # 'pizza'
category_object = Category.objects.get(name=category_name) # Object
item = Item(category=category_object, **validated_data)
item.save()
return item
# item/views.py
# Item 기능
class ItemView(APIView):
# Item 조회 기능
def get(self, request):
...
# Item 생성 기능
def post(self, request):
item_serializer = ItemSerializer(data=request.data)
if item_serializer.is_valid():
item_serializer.save()
return Response({'message': '저장 완료!'}, status=status.HTTP_200_OK)
return Response(item_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
조건 : 주문id가 일치하고 Order모델의 order_date 범위가 현재시간 기준으로 일주일전까지의 주문내역만 조회하도록 구현 (Q객체 사용)
# item/views.py
# order 기능
class OrderView(APIView):
# id로 order 조회 기능
def get(self, request):
order_id = request.GET['order_id']
time = timezone.now() - timedelta(days=7)
# time = timezone.now()
# 조건 = query
query = Q(id=order_id) & Q(order_date__gte=time)
order_object = Order.objects.get(query)
return Response(OrderSerializer(order_object).data)
https://github.com/kimphysicsman/nbcamp-quiz-220623