Skip to content

Commit

Permalink
speed up backend:))
Browse files Browse the repository at this point in the history
  • Loading branch information
August Fu committed Feb 28, 2024
1 parent 1a3de20 commit a815007
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 41 deletions.
39 changes: 39 additions & 0 deletions backend/courses/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,45 @@ class Meta:
]
read_only_fields = fields

class SimpleCourseSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField(
source="full_code",
help_text=dedent(
"""
The full code of the course, in the form '{dept code}-{course code}'
dash-joined department and code of the course, e.g. `CIS-120` for CIS-120."""
),
)

course_quality = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=course_quality_help
)
difficulty = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=difficulty_help
)
instructor_quality = serializers.DecimalField(
max_digits=4,
decimal_places=3,
read_only=True,
help_text=instructor_quality_help,
)
work_required = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=work_required_help
)

class Meta:
model = Course
fields = [
"id",
"title",
"credits",
"semester",
"course_quality",
"instructor_quality",
"difficulty",
"work_required",
]
read_only_fields = fields

class CourseDetailSerializer(CourseListSerializer):
crosslistings = serializers.SlugRelatedField(
Expand Down
19 changes: 9 additions & 10 deletions backend/degree/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from rest_framework import serializers

from courses.models import Course
from courses.serializers import CourseListSerializer, CourseDetailSerializer
from courses.serializers import CourseListSerializer, CourseDetailSerializer, SimpleCourseSerializer
from degree.models import Degree, DegreePlan, DoubleCountRestriction, Fulfillment, Rule
from courses.util import get_current_semester

Expand Down Expand Up @@ -54,7 +54,7 @@ class FulfillmentSerializer(serializers.ModelSerializer):
def get_course(self, obj):
course = Course.with_reviews.filter(full_code=obj.full_code, semester__lte=get_current_semester()).order_by("-semester").first()
if course is not None:
return CourseDetailSerializer(course).data
return SimpleCourseSerializer(course).data
return None

# TODO: add a get_queryset method to only allow rules from the degree plan
Expand Down Expand Up @@ -120,14 +120,13 @@ class DegreePlanDetailSerializer(serializers.ModelSerializer):
read_only=True,
help_text="The courses used to fulfill degree plan.",
)
degrees = DegreeDetailSerializer(read_only=True, many=True)
degree_ids = serializers.PrimaryKeyRelatedField(
many=True,
required=False,
source="degrees",
queryset=Degree.objects.all(),
help_text="The degree_id this degree plan belongs to.",
)
# degree_ids = serializers.PrimaryKeyRelatedField(
# many=True,
# required=False,
# source="degrees",
# queryset=Degree.objects.all(),
# help_text="The degree_id this degree plan belongs to.",
# )
person = serializers.HiddenField(default=serializers.CurrentUserDefault())

class Meta:
Expand Down
13 changes: 10 additions & 3 deletions backend/degree/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,22 @@ class DegreeViewset(viewsets.ReadOnlyModelViewSet):
Retrieve a list of all Degree objects.
"""

queryset = Degree.objects.all()
# queryset = Degree.objects.all()
filter_backends = [DjangoFilterBackend, SearchFilter]
search_fields = ["program", "degree", "concentration", "year"]
filterset_fields = search_fields

def get_queryset(self):
queryset = Degree.objects.all()
degree_id = self.request.query_params.get('id', None)
if degree_id is not None:
queryset = queryset.filter(id=degree_id)
return queryset

def get_serializer_class(self):
if self.action == "list":
if self.request.query_params.get('id', None) is not None:
return DegreeDetailSerializer
return DegreeListSerializer
return DegreeDetailSerializer

Expand Down Expand Up @@ -64,11 +73,9 @@ def get_serializer_context(self):
return context

def retrieve(self, request, *args, **kwargs):
print('aha')
degree_plan = self.get_object()
serializer = self.get_serializer(degree_plan)
# print(serializer.data)
print(type(serializer.data))
return Response(serializer.data, status=status.HTTP_200_OK)

@action(detail=True, methods=["post"])
Expand Down
1 change: 0 additions & 1 deletion frontend/degree-plan/components/Requirements/QObject.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,6 @@ interface RuleLeafProps {
}

const RuleLeaf = ({ q_json, fulfillmentsForRule, rule, satisfied }: RuleLeafProps) => {
console.log(q_json)
const t1 = transformDepartmentInClauses(q_json);
const t2 = transformCourseClauses(t1);
const t3 = transformSearchConditions(t2)
Expand Down
33 changes: 18 additions & 15 deletions frontend/degree-plan/components/Requirements/ReqPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Degree, DegreePlan, Fulfillment, Rule } from '@/types';
import styled from '@emotion/styled';
import { EditButton, PanelBody, PanelContainer, PanelHeader, PanelTopBarIcon, PanelTopBarIconList, TopBarIcon } from '@/components/FourYearPlan/PlanPanel'
import { useSWRCrud } from '@/hooks/swrcrud';
import useSWR from 'swr';
import useSWR, { useSWRConfig } from 'swr';
import { GrayIcon, Icon } from '../common/bulma_derived_components';
import React from 'react';

Expand Down Expand Up @@ -119,25 +119,28 @@ const DegreeHeader = ({ degree, remove, setCollapsed, collapsed, editMode }: { d
)
}

const Degree = ({degree, rulesToFulfillments, activeDegreeplan, editMode, setModalKey, setModalObject}: any) => {
const Degree = ({degree_id, rulesToFulfillments, activeDegreeplan, editMode, setModalKey, setModalObject}: any) => {
const [collapsed, setCollapsed] = useState(false);
const { data: degree, isLoading: isLoadingDegrees } = useSWR<Degree[]>(activeDegreeplan ? `/api/degree/degrees/?id=${degree_id}`: null);
// const { cache, mutate, } = useSWRConfig();

return (
<div>
{degree &&
<DegreeHeader
degree={degree}
key={degree.id}
remove={() => {
setModalObject({degreeplanId: activeDegreeplan.id, degreeId: degree.id});
setModalKey("degree-remove");
}}
setCollapsed={setCollapsed}
collapsed={collapsed || editMode} // Collapse degree view in edit mode
editMode={editMode}
/>
degree={degree[0]}
key={degree_id}
remove={() => {
setModalObject({degreeplanId: activeDegreeplan.id, degreeId: degree_id});
setModalKey("degree-remove");
}}
setCollapsed={setCollapsed}
collapsed={collapsed || editMode} // Collapse degree view in edit mode
editMode={editMode}
/>}
{!collapsed && !editMode &&
<DegreeBody>
{degree.rules.map((rule: any) => (
{degree && degree[0].rules.map((rule: any) => (
<RuleComponent
rulesToFulfillments={rulesToFulfillments}
activeDegreePlanId={activeDegreeplan.id}
Expand Down Expand Up @@ -200,9 +203,9 @@ const ReqPanel = ({setModalKey, setModalObject, activeDegreeplan, isLoading, set
</PanelHeader>
{!activeDegreeplan ? <EmptyPanel /> :
<PanelBody>
{activeDegreeplan.degrees.map(degree => (
{activeDegreeplan.degrees.map(degree_id => (
<Degree
degree={degree}
degree_id={degree_id}
rulesToFulfillments={rulesToFulfillments}
activeDegreeplan={activeDegreeplan}
setSearchClosed={setSearchClosed}
Expand Down
23 changes: 13 additions & 10 deletions frontend/degree-plan/pages/FourYearPlanPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from "../components/Search/SearchPanel";
// import Plan from "../components/example/Plan";
import styled from "@emotion/styled";
import useSWR from "swr";
import useSWR, { useSWRConfig } from "swr";
import { Course, DegreePlan, Options, Rule } from "@/types";
import ReviewPanel from "@/components/Infobox/ReviewPanel";
import { ReviewPanelContext } from "@/components/Infobox/ReviewPanel";
Expand Down Expand Up @@ -77,24 +77,27 @@ const FourYearPlanPage = ({ updateUser, user, activeDegreeplanId, setActiveDegre
: null
);

console.log(activeDegreePlan);

useEffect(() => {
console.log('detect change in degreeplans');
// recompute the active degreeplan id on changes to the degreeplans
if (!isLoadingDegreeplans && !degreeplans?.length) {
setShowOnboardingModal(true);
}
if (!degreeplans?.length) {
setActiveDegreeplanId(null);
}
// else if (degreeplans.length > 0) {
// setActiveDegreeplanId(degreeplans[0].id);
// }
else if (!activeDegreeplanId || !degreeplans.find((d) => d.id === activeDegreeplanId)
) {
const mostRecentUpdated = degreeplans.reduce((a, b) =>
a.updated_at > b.updated_at ? a : b
);
setActiveDegreeplanId(mostRecentUpdated.id);
else if (degreeplans.length > 0) {
setActiveDegreeplanId(degreeplans[1].id);
}
// else if (!activeDegreeplanId || !degreeplans.find((d) => d.id === activeDegreeplanId)
// ) {
// const mostRecentUpdated = degreeplans.reduce((a, b) =>
// a.updated_at > b.updated_at ? a : b
// );
// setActiveDegreeplanId(mostRecentUpdated.id);
// }
}, [degreeplans]);

const windowWidth = useWindowDimensions()["width"];
Expand Down
1 change: 1 addition & 0 deletions frontend/degree-plan/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export default function Home() {
value={{
fetcher: (resource, init) =>
fetch(resource, init).then((res) => res.json()),
provider: () => new Map(),
onError: (error, key) => {
if (error.status !== 403 && error.status !== 404) {
// error handling
Expand Down
3 changes: 1 addition & 2 deletions frontend/degree-plan/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ export interface Degree extends DBObject {

export interface DegreePlan extends DBObject {
id: number;
degrees: Degree[];
degree_ids: number[]; // the ids of the degrees in the degree plan, which we use to mutate the degree plan
degrees: number[]; // the ids of the degrees in the degree plan, which we use to mutate the degree plan
name: string;
updated_at: string;
created_at: string;
Expand Down

0 comments on commit a815007

Please sign in to comment.