Skip to content

Commit

Permalink
1.management command to populate db, 2.sample api to search by category
Browse files Browse the repository at this point in the history
  • Loading branch information
Amey Tendulkar committed Oct 29, 2023
1 parent 2841d6f commit 008c6c5
Show file tree
Hide file tree
Showing 7 changed files with 135 additions and 7 deletions.
83 changes: 83 additions & 0 deletions api/management/commands/populateDb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from django.core.management.base import BaseCommand
import random
from datetime import datetime, timedelta
from faker import Faker
from api.models import *

categories = ['Fresh', 'Books', 'Sports', 'Electronics', 'Fashion']
subcategories = {
'Fresh': ['Fruits & Vegetables', 'Dairy & Bread', 'Snacks', 'Instant Food'],
'Books': ['Fiction', 'Children', 'Academic', 'Travel', 'History'],
'Sports': ['Cricket', 'Football', 'Badminton', 'Running', 'Cycling', 'Accesories'],
'Electronics': ['Mobiles', 'Laptops', 'Televisions', 'Cameras', 'Home Appliances'],
'Fashion': ['Men Clothing', 'Women Clothing', 'Shoes', 'Accesories'],
}
fake = Faker()

class Command(BaseCommand):
help = 'Custom management command description'

def handle(self, *args, **options):
Product.objects.all().delete()
SubCategory.objects.all().delete()
Category.objects.all().delete()

#code to add category and subcategory
bulk_add_categories = []
for category in categories:
category_obj = Category(name=category)
bulk_add_categories.append(category_obj)

Category.objects.bulk_create(bulk_add_categories)

category_objects = {}
categories_objects = Category.objects.all()
for category in categories_objects:
category_objects[category.name] = category

bulk_add_sub_categories = []
for category, subcategory_list in subcategories.items():
category_object = category_objects[category]
for sub_cat_name in subcategory_list:
subcategory_obj = SubCategory(name=sub_cat_name, category=category_object)
bulk_add_sub_categories.append(subcategory_obj)

SubCategory.objects.bulk_create(bulk_add_sub_categories)
subcategory_objects = {}
subcategories_objects = SubCategory.objects.all()
for subcategory in subcategories_objects:
subcategory_objects[subcategory.name] = subcategory

print('now generating products.............')
#generate fake data using faker.
def generate_product():
category_name = random.choice(categories)
subcategory_name = random.choice(subcategories[category_name])

product = {
'sub_category': subcategory_name,
'name': fake.word(),
'price': round(random.uniform(1, 1000), 2),
'description': fake.sentence(),
'stock': random.randint(0, 100),
'rating': round(random.uniform(1, 5), 2),
'reviews': [{'author': fake.name(), 'comment': fake.paragraph(), 'rating': random.randint(1, 5)} for _ in range(random.randint(0, 5))],
'additional_info': {
'brand': fake.company(),
'model': fake.word(),
},
'is_active': random.choice([True, False]),
'created_at': (datetime.now() - timedelta(days=random.randint(1, 365))).strftime("%Y-%m-%dT%H:%M:%S"),
}

return product
bulk_add_products = []
for i in range(0,300):
product = generate_product()
sub_category_obj = subcategory_objects[product['sub_category']]
product_obj = Product(sub_category=sub_category_obj, name=product['name'], price=product['price'], description=product['description'], stock=product['stock'], rating=product['rating'], reviews={'reviews':product['reviews']}, additional_info=product['additional_info'], is_active=product['is_active'], created_at=product['created_at'])
bulk_add_products.append(product_obj)

Product.objects.bulk_create(bulk_add_products)
self.stdout.write(self.style.SUCCESS('Successfully executed your custom script'))

17 changes: 17 additions & 0 deletions api/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from rest_framework import serializers
from api.models import *

class SubCategorySerializer(serializers.ModelSerializer):
class Meta:
model = SubCategory
fields = '__all__'

class ProductSerializer(serializers.ModelSerializer):
sub_category = serializers.SerializerMethodField()

def get_sub_category(self, product):
subcategory = SubCategorySerializer(product.sub_category)
return subcategory.data
class Meta:
model = Product
fields = '__all__'
7 changes: 7 additions & 0 deletions api/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from api.views import ProductsByCategory
from django.urls import path

urlpatterns = [
path('products-by-category/<int:id>', ProductsByCategory.as_view()),

]
23 changes: 21 additions & 2 deletions api/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
from django.shortcuts import render
from rest_framework.views import APIView
from django.http import JsonResponse
import json
from rest_framework import status as api_response_status
from api.models import *
from api.serializers import *

# Create your views here.
class ProductsByCategory(APIView):

def get(self, request, id, format=None):

category = Category.objects.get(id=id)
subcategories = SubCategory.objects.filter(category=category)
products = Product.objects.filter(sub_category__in=subcategories)

products = ProductSerializer(products, many=True)

return JsonResponse({
'success': True,
'userMessage': '',
'data': products.data,
}, status = api_response_status.HTTP_200_OK)
8 changes: 4 additions & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ version: '3.8'

services:
webserver:
container_name: webserver
container_name: webserver-globalmart
build: ./
command: sh -c "python manage.py runserver 0.0.0.0:8000"
volumes:
Expand All @@ -13,7 +13,7 @@ services:
- db

db:
container_name: db
container_name: db-master-globalmart
image: postgres:14.7-alpine
volumes:
- pgdata:/var/lib/postgresql/data/
Expand All @@ -25,14 +25,14 @@ services:
- POSTGRES_DB=globalmart

pgadmin:
container_name: pgadmin4
container_name: pgadmin4-globalmart
image: dpage/pgadmin4
restart: always
environment:
PGADMIN_DEFAULT_EMAIL: [email protected]
PGADMIN_DEFAULT_PASSWORD: root123
ports:
- "5050:80"
- "5051:80"

volumes:
pgdata:
Expand Down
3 changes: 2 additions & 1 deletion globalmart/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path, include

urlpatterns = [
path('api/', include("api.urls")),
path("admin/", admin.site.urls),
]
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ typing_extensions==4.7.1
tzdata==2023.3
psycopg2==2.9.6
djangorestframework==3.14.0
Faker==19.12.0

0 comments on commit 008c6c5

Please sign in to comment.