Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MIL-107 m2m связь пользователей, направлений и уровней #403

Open
wants to merge 9 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 34 additions & 6 deletions src/lizaalert/courses/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
CourseFaq,
CourseKnowledge,
CourseProgressStatus,
Division,
Knowledge,
Lesson,
LessonProgressStatus,
Expand Down Expand Up @@ -65,6 +66,14 @@ def get_chapter_link(self, obj):
get_chapter_link.short_description = "Глава"


class DivisionInline(admin.StackedInline):
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
"""Инлайн направления для отображения в главе."""

model = Division
min_num = 1
extra = 0


@admin.register(Cohort)
class CohortAdmin(admin.ModelAdmin):
"""
Expand Down Expand Up @@ -97,6 +106,9 @@ class CourseAdmin(admin.ModelAdmin):
"""Админка курса."""

inlines = (CourseFaqInline, CourseKnowledgeInline, ChapterInline)
list_filter = [
"division",
]
model = Course
list_display = (
"title",
Expand All @@ -105,6 +117,7 @@ class CourseAdmin(admin.ModelAdmin):
"user_created",
"created_at",
"updated_at",
"division",
)
ordering = ("-updated_at",)
empty_value_display = "-пусто-"
Expand Down Expand Up @@ -228,12 +241,7 @@ class KnowledgeAdmin(admin.ModelAdmin):

inlines = (CourseKnowledgeInline,)
ordering = ("-updated_at",)
list_display = (
"title",
"author",
"created_at",
"updated_at",
)
list_display = ("title", "author", "created_at", "updated_at")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

оставь как было



@admin.register(Lesson)
Expand Down Expand Up @@ -278,3 +286,23 @@ class SubscriptionAdmin(admin.ModelAdmin):
]

ordering = ("-updated_at",)


@admin.register(Division)
class DivisionAdmin(admin.ModelAdmin):
"""Aдминка для Division."""

ordering = ("-updated_at",)
list_display = ("title", "author", "created_at", "updated_at", "courses")
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
list_select_related = ("author",)
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved

@admin.display(description="Курсы")
def courses(self, obj):
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
return list(obj.course_set.all().values_list("title", flat=True))
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved

def get_queryset(self, request):
qs = self.model._default_manager.get_queryset().prefetch_related("course_set")
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
41 changes: 41 additions & 0 deletions src/lizaalert/courses/migrations/0027_auto_20240229_2149.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Generated by Django 3.2.20 on 2024-02-29 18:49

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


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('courses', '0026_alter_lesson_lesson_type'),
]

operations = [
migrations.CreateModel(
name='Division',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True, db_index=True)),
('deleted_at', models.DateTimeField(blank=True, null=True)),
('title', models.CharField(max_length=250, verbose_name='Название направления')),
('description', models.CharField(max_length=1000, verbose_name='Описание направления')),
('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='Создатель направления')),
],
options={
'verbose_name': 'Направление',
'verbose_name_plural': 'Направления',
},
),
migrations.AddField(
model_name='course',
name='division',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='courses.division', verbose_name='Направление курса'),
),
migrations.AddConstraint(
model_name='division',
constraint=models.UniqueConstraint(fields=('title',), name='unique_division'),
),
]
21 changes: 20 additions & 1 deletion src/lizaalert/courses/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ class Knowledge(TimeStampedModel):
author = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Создатель умения")

class Meta:
constraints = [models.UniqueConstraint(fields=["title"], name="unique_knowledge")]
constraints = [
models.UniqueConstraint(fields=("title",), name="unique_knowledge"),
]
verbose_name = "Умение"
verbose_name_plural = "Умения"

Expand Down Expand Up @@ -118,6 +120,9 @@ class CourseStatus(models.IntegerChoices):
)
user_created = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Создатель курса")
status = models.IntegerField(verbose_name="статус курса", choices=CourseStatus.choices, default=CourseStatus.DRAFT)
division = models.ForeignKey(
"courses.Division", on_delete=models.PROTECT, verbose_name="Направление курса", null=True, blank=True
)

class Meta:
verbose_name = "Курс"
Expand Down Expand Up @@ -587,3 +592,17 @@ def finish(self):
"""Завершить подписку на курс."""
self.status = Subscription.Status.COMPLETED
self.save()


class Division(TimeStampedModel):
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
title = models.CharField(max_length=250, verbose_name="Название направления")
description = models.CharField(max_length=1000, verbose_name="Описание направления")
author = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Создатель направления")

class Meta:
constraints = [models.UniqueConstraint(fields=["title"], name="unique_division")]
verbose_name = "Направление"
verbose_name_plural = "Направления"

def __str__(self):
return f"<Division: {self.id}, title: {self.title}>"
19 changes: 18 additions & 1 deletion src/lizaalert/users/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
Level,
Location,
User,
UserDivisionLevel,
UserRole,
Volunteer,
VolunteerBadge,
Expand Down Expand Up @@ -36,6 +37,11 @@ class LevelAdmin(admin.ModelAdmin):
inlines = [VolunteerLevelInline]


class UserDivisionLevelInline(admin.TabularInline):
model = UserDivisionLevel
extra = 1


class BadgeAdminForm(forms.ModelForm):
class Meta:
model = Badge
Expand Down Expand Up @@ -102,7 +108,17 @@ def clean(self):


class VolunteerAdmin(admin.ModelAdmin):
inlines = [VolunteerLevelInline, VolunteerBadgeInline]
inlines = [VolunteerLevelInline, VolunteerBadgeInline, UserDivisionLevelInline]


class UserDivisionLevelAdmin(admin.ModelAdmin):
list_display = ("__str__", "volunteer", "division", "level")
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
list_display_links = ("volunteer",)
list_filter = (
"volunteer",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

волонтера добавь в raw_field

"division",
"level",
)


admin.site.register(User, CustomUserAdmin)
Expand All @@ -113,3 +129,4 @@ class VolunteerAdmin(admin.ModelAdmin):
admin.site.register(Department)
admin.site.register(Badge, BadgeAdmin)
admin.site.register(Level, LevelAdmin)
admin.site.register(UserDivisionLevel, UserDivisionLevelAdmin)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

отдельно таблицу связей отображать не надо

в карточке пользователя добавь отображение списка направлений

24 changes: 24 additions & 0 deletions src/lizaalert/users/migrations/0008_auto_20240229_2149.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 3.2.20 on 2024-02-29 18:49

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


class Migration(migrations.Migration):

dependencies = [
('courses', '0027_auto_20240229_2149'),
('users', '0007_badge_badge_slug'),
]

operations = [
migrations.AddField(
model_name='badge',
name='division',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='courses.division', verbose_name='Направление умения'),
),
migrations.AddConstraint(
model_name='badge',
constraint=models.UniqueConstraint(fields=('name', 'division'), name='unique_badge'),
),
]
29 changes: 29 additions & 0 deletions src/lizaalert/users/migrations/0009_auto_20240303_2149.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Generated by Django 3.2.20 on 2024-03-03 18:49

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


class Migration(migrations.Migration):

dependencies = [
('courses', '0027_auto_20240229_2149'),
('users', '0008_auto_20240229_2149'),
]

operations = [
migrations.CreateModel(
name='UserDivisionLevel',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('division', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='courses.division', verbose_name='Направление умения')),
('level', models.ForeignKey(default='novice', on_delete=django.db.models.deletion.PROTECT, to='users.level', verbose_name='Уровень умения')),
('volunteer', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='divisionlevels', to='users.volunteer', verbose_name='Волонтер')),
],
),
migrations.AddField(
model_name='volunteer',
name='divisionlevel',
field=models.ManyToManyField(blank=True, related_name='volunteers', through='users.UserDivisionLevel', to='courses.Division', verbose_name='Уровень умения'),
),
]
35 changes: 35 additions & 0 deletions src/lizaalert/users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,14 @@ class BadgeCategory(models.TextChoices):
blank=True,
verbose_name="Курс для получения",
)
division = models.ForeignKey(
"courses.Division", on_delete=models.PROTECT, verbose_name="Направление умения", null=True, blank=True
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
)

class Meta:
constraints = [
models.UniqueConstraint(fields=("name", "division"), name="unique_badge"),
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
]
db_table = "badges"
verbose_name = "Значок"
verbose_name_plural = "Значки"
Expand Down Expand Up @@ -296,6 +302,13 @@ class Volunteer(models.Model):
)
created_at = models.DateTimeField("Дата и время создания запси", auto_now_add=True)
updated_at = models.DateTimeField("Дата обновления записи", auto_now=True)
divisionlevel = models.ManyToManyField(
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
"courses.Division",
through="users.UserDivisionLevel",
blank=True,
related_name="volunteers",
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь указывается имя для обратной связи,

related_name="+",

verbose_name="Уровень умения",
)

class Meta:
db_table = "volunteers"
Expand All @@ -321,3 +334,25 @@ def create_default_volunteer_level(sender, instance, created, **kwargs):

if not existing_record:
VolunteerLevel.objects.create(volunteer=volunteer, level=beginner_level, confirmed=True)


class UserDivisionLevel(models.Model):
"""Модель для связи пользователей, направлений и уровней."""

volunteer = models.ForeignKey(
Volunteer,
on_delete=models.PROTECT,
related_name="divisionlevels",
verbose_name="Волонтер",
)
division = models.ForeignKey("courses.Division", on_delete=models.PROTECT, verbose_name="Направление умения")
level = models.ForeignKey(
Level, on_delete=models.PROTECT, verbose_name="Уровень умения", default=Level.LevelName.beginner
)
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved

class Meta:
verbose_name = "Уровень волонтера по направлениям"
verbose_name_plural = "Уровни волонтеров по направлениям"

def __str__(self):
return f"Уровень {self.volunteer.user} {self.level.name} в направлении {self.division.title}"
Leontiev93 marked this conversation as resolved.
Show resolved Hide resolved
Loading