from django.conf import settings
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.dispatch import receiver
# Create your models here.
class course_categories(models.Model):
deleted_flag = [('y', 'yes'), ('n', 'no')]
category_name = models.CharField(max_length=50, unique=True)
category_slug = models.SlugField(max_length=100, unique=True)
course_categories_code = models.CharField(max_length=7, unique=True)
created_by = models.CharField(max_length=50, null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=50, blank=True, null=True)
modified_date = models.DateTimeField(
auto_now_add=False, blank=True, null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')
def __str__(self):
return self.category_name
def create_course_category_slug(instance, new_slug=None):
slug = slugify(instance.category_name)
if new_slug is not None:
slug = new_slug
slug = "%s-%s" % (slug, instance.course_categories_code)
qs = course_categories.objects.filter(category_slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_course_category_slug(instance, new_slug=new_slug)
print("slug", slug)
return slug
@receiver(pre_save, sender=course_categories)
def pre_save_course_categories_receiver(sender, instance, *args, **kwargs):
# if not instance.category_slug:
instance.category_slug = create_course_category_slug(instance)
class courses(models.Model):
deleted_flag = [('y', 'yes'), ('n', 'no')]
course_name = models.CharField(max_length=70)
course_categories = models.ForeignKey(
'course_categories', related_name='courses', on_delete=models.CASCADE)
course_slug = models.SlugField(unique=True)
course_code = models.CharField(max_length=7, unique=True)
created_by = models.CharField(max_length=50, null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=50, blank=True, null=True)
modified_date = models.DateTimeField(
auto_now_add=False, blank=True, null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')
def __str__(self):
return self.course_name
def create_course_slug(instance, new_slug=None):
slug = slugify(instance.course_name)
if new_slug is not None:
slug = new_slug
slug = "%s-%s" % (slug, instance.course_code)
qs = courses.objects.filter(course_slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_course_slug(instance, new_slug=new_slug)
print("slug", slug)
return slug
@receiver(pre_save, sender=courses)
def pre_save_course_receiver(sender, instance, *args, **kwargs):
# if not instance.category_slug:
print("course")
instance.course_slug = create_course_slug(instance)
class subcourse(models.Model):
deleted_flag = [('y', 'yes'), ('n', 'no')]
subcourse_name = models.CharField(max_length=50, unique=True)
courses = models.ForeignKey(
'courses', related_name="subcourse", on_delete=models.CASCADE)
subcourse_slug = models.SlugField(unique=True)
subcourse_code = models.CharField(max_length=7, unique=True)
subcourse_short_description = models.CharField(max_length=150, blank=True)
created_by = models.CharField(max_length=50)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=50, blank=True, null=True)
modified_date = models.DateTimeField(
auto_now_add=False, blank=True, null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')
def __str__(self):
return self.subcourse_name
def create_subcourse_slug(instance, new_slug=None):
slug = slugify(instance.subcourse_name)
if new_slug is not None:
slug = new_slug
slug = "%s-%s" % (slug, instance.subcourse_code)
qs = subcourse.objects.filter(subcourse_slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_subcourse_slug(instance, new_slug=new_slug)
print("slug", slug)
return slug
@receiver(pre_save, sender=subcourse)
def pre_save_subcourse_receiver(sender, instance, *args, **kwargs):
# if not instance.category_slug:
print("course")
instance.subcourse_slug = create_subcourse_slug(instance)
class course_description(models.Model):
pass
from rest_framework import serializers
from .models import course_categories, courses, subcourse
from course_setup.serializers import MainTopicSerializer
class CourseCategorySerializerRedesign(serializers.ModelSerializer):
value = serializers.IntegerField(source="id")
label = serializers.CharField(source="category_name")
class Meta:
model = course_categories
fields = ('value', 'label')
class SubCourseSerializers(serializers.ModelSerializer):
course_name = serializers.SerializerMethodField(read_only=True)
subcourse_main_topic = MainTopicSerializer(many=True)
class Meta:
model = subcourse
fields = ('id', 'subcourse_name', 'courses', 'subcourse_slug', 'subcourse_code',
'subcourse_short_description', 'courses', 'course_name','subcourse_main_topic')
def get_course_name(self, instance):
return instance.courses.course_name
class CourseSerializerView(serializers.ModelSerializer):
# subcourse = SubcourseSerializerView()
class Meta:
model = courses
fields = ('id', 'course_name', 'course_code', 'course_categories')
class SubcourseSerializerView(serializers.ModelSerializer):
# courses = CourseSerializerView()
class Meta:
model = subcourse
fields = ('id', 'subcourse_name',
'subcourse_code', 'courses')
# depth = 2
class CourseSerializers(serializers.ModelSerializer):
subcourse = SubCourseSerializers(many=True, read_only=True)
class Meta:
model = courses
fields = ('__all__')
class CourseCategorySerializers(serializers.ModelSerializer):
# courses = CourseSerializers(many=True)
class Meta:
model = course_categories
fields = ('id', 'category_name', 'course_categories_code')
class GetCourseCategorySerializer(serializers.ModelSerializer):
class Meta:
model = course_categories
fields = ('id', 'category_name', 'course_categories_code',
'category_slug')
class CourseCategoryTreeSerializer(serializers.ModelSerializer):
courses = serializers.SerializerMethodField('get_children')
def get_children(self, course_categories):
serialized_data = CourseSerializers(course_categories.courses.all(
), many=True, read_only=True, context=self.context)
return serialized_data.data
class Meta:
model = course_categories
fields = ('id', 'category_name', 'course_categories_code',
'category_slug', 'courses')
from dataclasses import fields
from pyexpat import model
from rest_framework import serializers
from .models import subcourse_main_topic,sub_topic,subcourse
class MainTopicSerializer(serializers.ModelSerializer):
class Meta:
model = subcourse_main_topic
fields='_all_'
class SubTopicSerializer(serializers.ModelSerializer):
class Meta:
model = sub_topic
fields='_all_'from django.db import models
from course_category.models import subcourse
from instructors.models import instructor
# Create your models here.
deleted_flag = [('y', 'yes'), ('n', 'no')]
class subcourse_main_topic(models.Model):
subcourse = models.ForeignKey('course_category.subcourse',related_name="subcourse",on_delete=models.CASCADE)
topic_title = models.CharField(max_length=255)
created_by = models.CharField(max_length=100)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=100)
modified_date = models.DateTimeField(auto_now_add=True)
modified_remarks = models.CharField(max_length=255,blank=True,null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')
class sub_topic(models.Model):
subcourse_main_topic_id = models.ForeignKey('subcourse_main_topic',related_name="subtopic",on_delete=models.CASCADE)
topic_title = models.CharField(max_length=255)
video_url = models.URLField()
preview_status = models.BooleanField(default=False)
resource_url = models.URLField(null=True,blank=True)
instructors = models.ForeignKey('instructors.instructor',related_name="instructors",on_delete=models.CASCADE)
created_by=models.CharField(max_length=70)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=70,null=True,blank=True)
modified_date = models.DateTimeField(null=True,blank=True)
modified_remarks = models.CharField(max_length=150,null=True,blank=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')from django.shortcuts import render
import base64
from .serializers import (
CourseCategorySerializers,
GetCourseCategorySerializer,
CourseSerializers,
CourseCategorySerializerRedesign,
CourseCategoryTreeSerializer,
SubCourseSerializers,
CourseSerializerView,
SubcourseSerializerView
)
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.parsers import JSONParser
from .models import course_categories, courses, subcourse
from rest_framework.generics import ListAPIView
from django.db.models import Prefetch
# Create your views here.
@api_view(['GET'],)
def get_all_course_category(request):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
queryset = course_categories.objects.all()
serializer = GetCourseCategorySerializer(queryset, many=True)
print(serializer.data)
# serializer.data['enc_id'] = base64.standard_b64encode(serializer.data.id)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
# return Response({'course_category': serializer.data})
return Response(result)
@api_view(['POST'])
def create_course_category_serializer(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
if request.method == 'POST':
serializer = CourseCategorySerializers(
data=request.data)
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Course category added successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': 'Operation Failed !!',
'type': 'form-error'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'],)
def get_course_category_by_id(request, slug):
# print("slug", slug)
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
try:
queryset = course_categories.objects.get(category_slug=slug)
# print("queryset", queryset)
serializer = GetCourseCategorySerializer(queryset, many=False)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result)
except course_categories.DoesNotExist:
result = {
'data': serializer.errors,
'response': False,
'msg': 'Data Doesnot exist !!'
}
return Response(result)
@api_view(['PATCH'])
def update_course_category_serializer(request):
if request.method == "PATCH":
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
category_id = request.data['category_id']
try:
category_data = course_categories.objects.get(pk=category_id)
serializer = CourseCategorySerializers(category_data, request.data)
if(serializer.is_valid()):
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Updated Successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': 'Operation Failed !!',
'type': 'form-error'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
except course_categories.DoesNotExist:
result = {
'data': request.data,
'response': False,
'msg': 'Data Doesnot exist !!'
}
return Response(result)
@api_view(['GET', ])
def get_course_category_select(request):
queryset = course_categories.objects.all()
serializer = CourseCategorySerializerRedesign(queryset, many=True)
return Response({'course_category': serializer.data})
@api_view(['GET', ])
def get_all_course(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
queryset = courses.objects.all()
serializer = CourseSerializers(queryset, many=True)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result)
@api_view(['POST', ])
def create_course(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
if request.method == "POST":
serializer = CourseSerializerView(data=request.data)
if (serializer.is_valid()):
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Course Added Successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', ])
def get_course_by_id(request, slug):
if request.method == 'GET':
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
try:
print("slug", slug)
getData = courses.objects.get(course_slug=slug)
serializer = CourseSerializers(getData, many=False)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result, status=status.HTTP_200_OK)
except courses.DoesNotExist:
result = {
'data': '',
'response': False,
'msg': 'Data Doesnot exist'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
@api_view(['PATCH', ])
def edit_course(request):
if request.method == "PATCH":
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
try:
course_id = request.data['course_id']
checkData = courses.objects.get(pk=course_id)
serializer = CourseSerializerView(checkData, request.data)
data = {}
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'updated successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
except courses.DoesNotExist:
result = {
'data': '',
'response': False,
'msg': 'Data doesnot exist'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', ])
def get_all_sub_course(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
queryset = subcourse.objects.select_related(
'courses')
serializers = SubCourseSerializers(queryset, many=True)
result = {
'data': serializers.data,
'response': True,
'msg': ''
}
return Response(result, status=status.HTTP_200_OK)
@api_view(['POST', ])
def create_sub_course(request):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed'
}
if request.method == "POST":
serializer = SubcourseSerializerView(data=request.data)
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Subcourse created successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', ])
def get_sub_course_by_slug(request, slug):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed!!'
}
if request.method == "GET":
try:
data = subcourse.objects.get(subcourse_slug=slug)
serializer = SubCourseSerializers(data, many=False)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result, status=status.HTTP_200_OK)
except subcourse.DoesNotExist:
result = {
'data': '',
'response': False,
'msg': 'Data Doesnot Exist '
}
return Response(result)
@api_view(['PATCH', ])
def edit_subcourse(request):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
if request.method == "PATCH":
try:
subcourse_id = request.data['subcourse_id']
checkData = subcourse.objects.get(pk=subcourse_id)
serializer = SubcourseSerializerView(checkData, data=request.data)
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Updated Successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
except subcourse.DoesNotExist:
result = {
'data': request.data,
'response': False,
'msg': 'Data Doesnot exist !!'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', ])
def get_course_tree_view(request):
# queryset = course_categories.objects.prefetch_related('courses')
children = Prefetch(
'courses__subcourse', queryset=subcourse.objects.select_related('courses'))
queryset = course_categories.objects.prefetch_related(children)
serializer = CourseCategoryTreeSerializer(queryset, many=True)
return Response(serializer.data)
Yes you canWhat's your model look like ?--hello folks,any django ex[ert here, I want to know if anybody can do multiple join more than 5 tables at once using ORM Prefetch,prefetch_related,select_related using any of these or in a different way please ping, or just write over here how can we solve that. i didn't get any cluehelp will be appreciated--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a2097a78-1446-4456-83a1-c96059a12a1dn%40googlegroups.com.
Oussama Chafiqui--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPvcp%2BVtMGtBmC5RZNn8k_-6WRhY9UCbMg%3DqjFZDH7dc81%2B%3DCw%40mail.gmail.com.
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEtntjVFE24MnzyE27jccambxLm63%3D4C1FH4%3D5Ls3h8mspOcyw%40mail.gmail.com.
No comments:
Post a Comment