Skip to content

Commit

Permalink
models
Browse files Browse the repository at this point in the history
  • Loading branch information
zachHarpaz committed Oct 13, 2024
1 parent 3c8596f commit 5d725aa
Show file tree
Hide file tree
Showing 13 changed files with 308 additions and 37 deletions.
7 changes: 2 additions & 5 deletions backend/penndata/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
Event,
FitnessRoom,
FitnessSnapshot,
HomePageOrder,
GlobalStat,
IndividualStat
HomePageOrder
)


Expand All @@ -27,5 +25,4 @@ def image_tag(self, instance):
admin.site.register(FitnessRoom, FitnessRoomAdmin)
admin.site.register(FitnessSnapshot)
admin.site.register(AnalyticsEvent)
admin.site.register(GlobalStat)
admin.site.register(IndividualStat)

33 changes: 1 addition & 32 deletions backend/penndata/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,35 +114,4 @@ class CalendarEvent(models.Model):
def __str__(self):
return f"{self.date}-{self.event}"



# Adding statistics tracking here
class GlobalStat(models.Model):
stat_key = models.CharField(max_length=50,
null=False, blank=False)
stat_value = models.CharField(max_length=50,
null=False, blank=False)
year = models.IntegerField()

class Meta:
unique_together = ("stat_key", "year")

def __str__(self):
return f"Global -- {self.stat_key}-{str(self.year)} : {self.stat_value}"

class IndividualStat(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
stat_key = models.CharField(max_length=50,
null=False, blank=False)
stat_value = models.CharField(max_length=50,
null=False, blank=False)
year = models.IntegerField()

class Meta:
unique_together = ("stat_key", "year", "user")

def __str__(self) -> str:
return f"User: {self.user} -- {self.stat_key}-{str(self.year)} : {self.stat_value}"




1 change: 1 addition & 0 deletions backend/pennmobile/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"accounts.apps.AccountsConfig",
"identity.apps.IdentityConfig",
"analytics.apps.AnalyticsConfig",
"wrapped.apps.WrappedConfig",
"django_filters",
"debug_toolbar",
"gsr_booking",
Expand Down
Empty file added backend/wrapped/__init__.py
Empty file.
66 changes: 66 additions & 0 deletions backend/wrapped/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from django.contrib import admin
from django.core.exceptions import ValidationError

from wrapped.models import GlobalStat, IndividualStat, UserStatKey, Template, Page


class WrappedIndividualAdmin(admin.ModelAdmin):
search_fields = ["user__username__icontains", "stat_key__stat_key__icontains", "semester__icontains"]
list_display = ["user", "stat_key", "stat_value", "semester"]


class WrappedGlobalAdmin(admin.ModelAdmin):

list_display = ["stat_key", "stat_value", "semester"]
search_fields = ["semester__icontains","stat_key__icontains"]



# class PageAdmin(admin.ModelAdmin):
# # Customize the admin interface for YourModel if needed
# list_display = ['template'] # Example field to display, modify as needed

# def save_related(self, request, form, formsets, change):
# super().save_related(request, form, formsets, change)

# # After saving the many-to-many relations, perform validation
# instance = form.instance

# # Count the IndividualStat and GlobalStat entries
# individual_stat_count = instance.IndividualStat.count()
# global_stat_count = instance.GlobalStat.count()

# print(individual_stat_count)

# total_stat_count = individual_stat_count + global_stat_count

# if total_stat_count != instance.template.num_fields:
# raise ValidationError(
# f"The total number of stats (IndividualStat + GlobalStat) "
# f"must equal the template's num_fields value ({instance.template.num_fields})."
# )

# # Validate that all stats are from the same semester
# individual_semesters = set(instance.IndividualStat.values_list('semester', flat=True))
# global_semesters = set(instance.GlobalStat.values_list('semester', flat=True))

# all_semesters = individual_semesters.union(global_semesters)

# if len(all_semesters) > 1:
# raise ValidationError("All IndividualStat and GlobalStat entries must be from the same semester.")

# Register the model with the custom admin class



# admin.site.register(WrappedIndividualAdmin, WrappedGlobalAdmin)
admin.site.register(IndividualStat, WrappedIndividualAdmin)
admin.site.register(GlobalStat, WrappedGlobalAdmin)
admin.site.register(UserStatKey)
admin.site.register(Template)
# admin.site.register(Page, PageAdmin)
admin.site.register(Page)




8 changes: 8 additions & 0 deletions backend/wrapped/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.apps import AppConfig


class WrappedConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'wrapped'
def ready(self):
import wrapped.signals # Import the file where your signal is defined
64 changes: 64 additions & 0 deletions backend/wrapped/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Generated by Django 5.0.2 on 2024-10-11 19:50

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Template',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('background', models.CharField(max_length=50)),
('template', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='UserStatKey',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('stat_key', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='GlobalStat',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('stat_key', models.CharField(max_length=50)),
('stat_value', models.CharField(max_length=50)),
('semester', models.CharField(max_length=5)),
],
options={
'unique_together': {('stat_key', 'semester')},
},
),
migrations.CreateModel(
name='Page',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('temp', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wrapped.template')),
],
),
migrations.CreateModel(
name='IndividualStat',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('stat_value', models.CharField(max_length=50)),
('semester', models.CharField(max_length=5)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('stat_key', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wrapped.userstatkey')),
],
options={
'unique_together': {('stat_key', 'semester', 'user')},
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Generated by Django 5.0.2 on 2024-10-11 20:38

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('wrapped', '0001_initial'),
]

operations = [
migrations.RemoveField(
model_name='page',
name='temp',
),
migrations.RemoveField(
model_name='template',
name='background',
),
migrations.RemoveField(
model_name='template',
name='template',
),
migrations.AddField(
model_name='page',
name='GlobalStat',
field=models.ManyToManyField(to='wrapped.globalstat'),
),
migrations.AddField(
model_name='page',
name='IndividualStat',
field=models.ManyToManyField(to='wrapped.individualstat'),
),
migrations.AddField(
model_name='page',
name='template',
field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, to='wrapped.template'),
preserve_default=False,
),
migrations.AddField(
model_name='template',
name='name',
field=models.CharField(default='test', max_length=10),
preserve_default=False,
),
migrations.AddField(
model_name='template',
name='num_fields',
field=models.IntegerField(default=1),
preserve_default=False,
),
migrations.AddField(
model_name='template',
name='template_path',
field=models.CharField(default='hhell', max_length=50),
preserve_default=False,
),
]
Empty file.
63 changes: 63 additions & 0 deletions backend/wrapped/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from django.db import models
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
User = get_user_model()


class GlobalStat(models.Model):

stat_key = models.CharField(max_length=50,
null=False, blank=False)

stat_value = models.CharField(max_length=50,
null=False, blank=False)

semester = models.CharField(max_length=5, null=False, blank=False)

class Meta:
unique_together = ("stat_key", "semester")

def __str__(self):
return f"Global -- {self.stat_key}-{str(self.semester)} : {self.stat_value}"


# Add a new model for keys
class UserStatKey(models.Model):
stat_key = models.CharField(max_length=50, null=False, blank=False)

def __str__(self) -> str:
return self.stat_key


class IndividualStat(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
stat_key = models.ForeignKey(UserStatKey, on_delete=models.CASCADE)

stat_value = models.CharField(max_length=50,
null=False, blank=False)
semester = models.CharField(max_length=5, null=False, blank=False)

class Meta:
unique_together = ("stat_key", "semester", "user")

def __str__(self) -> str:
return f"User: {self.user} -- {self.stat_key}-{str(self.semester)} : {self.stat_value}"

class Template(models.Model):

# Some file path
name = models.CharField(max_length=10, null=False, blank=False)
template_path = models.CharField(max_length=50, null=False, blank=False)
num_fields = models.IntegerField()
def __str__(self) -> str:
return f"{self.name}"


class Page(models.Model):

# How to do this, using individual vs stat_key ?

template = models.ForeignKey(Template, on_delete=models.CASCADE, null=False, blank=False)
IndividualStat = models.ManyToManyField(IndividualStat, blank=True)
GlobalStat = models.ManyToManyField(GlobalStat, blank=True)

34 changes: 34 additions & 0 deletions backend/wrapped/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# from django.db.models.signals import m2m_changed
# from django.core.exceptions import ValidationError
# from django.db import transaction
# from django.dispatch import receiver
# from wrapped.models import Page

# @receiver(m2m_changed, sender=Page.IndividualStat.through)
# @receiver(m2m_changed, sender=Page.GlobalStat.through)
# def validate_stats(sender, instance, action, **kwargs):
# if action == "post_add" or action == "post_remove" or action == "post_clear":
# transaction.on_commit(lambda: perform_validation(instance))

# def perform_validation(instance):
# individual_stat_count = instance.IndividualStat.count()
# global_stat_count = instance.GlobalStat.count()
# total_stat_count = individual_stat_count + global_stat_count

# print(f"Total stat change: {total_stat_count}")
# print(f"Individual stat change: {individual_stat_count}")
# print(f"Global stat change: {global_stat_count}")

# if total_stat_count != instance.template.num_fields:
# raise ValidationError(
# f"The total number of stats (IndividualStat + GlobalStat) "
# f"must equal the template's num_fields value ({instance.template.num_fields})."
# )

# individual_semesters = set(instance.IndividualStat.values_list('semester', flat=True))
# global_semesters = set(instance.GlobalStat.values_list('semester', flat=True))

# all_semesters = individual_semesters.union(global_semesters)

# if len(all_semesters) > 1:
# raise ValidationError("All IndividualStat and GlobalStat entries must be from the same semester.")
3 changes: 3 additions & 0 deletions backend/wrapped/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
6 changes: 6 additions & 0 deletions backend/wrapped/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.db import transaction
from wrapped.models import Page, IndividualStat, GlobalStat
from django.core.exceptions import ValidationError

0 comments on commit 5d725aa

Please sign in to comment.