Skip to content

Commit

Permalink
docs: updated docstrings in clients app
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-lymar committed Jun 29, 2024
1 parent 13ddaa2 commit b7548c6
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 14 deletions.
18 changes: 12 additions & 6 deletions clients/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@


class DirectorPosition(models.Model):
director_position = models.CharField(max_length=40)
"""
Model representing a director's position.
"""
director_position = models.CharField(max_length=40, verbose_name="Должность директора")

class Meta:
verbose_name = "Должность директора"
Expand All @@ -16,7 +19,10 @@ def __str__(self) -> str:


class Client(models.Model):
# Основная информация
"""
Model representing a client organization.
"""
# Main Information
client_name = models.CharField(
max_length=100, verbose_name="Наименование организации", db_index=True
)
Expand All @@ -31,7 +37,7 @@ class Client(models.Model):
destination_city = models.ForeignKey(
City, on_delete=models.PROTECT, verbose_name="Город доставки", db_index=True
)
# ЖД реквизиты
# Railway Details
railway_station = models.ForeignKey(
RailwayStation,
on_delete=models.PROTECT,
Expand All @@ -40,19 +46,19 @@ class Client(models.Model):
blank=True,
null=True,
)
# Остальные данные
# Other Data
receiver_name = models.CharField(max_length=100, blank=True, verbose_name="Имя получателя")
receiver_id = models.PositiveIntegerField(
blank=True, null=True, verbose_name="Номер получателя"
)
receiver_okpo = models.PositiveIntegerField(blank=True, null=True, verbose_name="ОКПО")
receiver_adress = models.CharField(max_length=200, blank=True, verbose_name="Адрес получателя")
special_marks = models.CharField(max_length=200, blank=True, verbose_name="Особые отметки")
# Номер приложения
# Application Number
last_application_number = models.CharField(
max_length=50, blank=True, verbose_name="Номер приложения"
)
# Пользователь который создал запись
# User who created the record
user = models.ForeignKey(
CustomUser,
verbose_name="Пользователь",
Expand Down
9 changes: 5 additions & 4 deletions clients/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@

class ClientAccessPermission(permissions.BasePermission):
"""
Класс разрешений для доступа к записям клиентов.
Проверяет, что пользователь аутентифицирован для просмотра записей.
Также проверяет, что пользователь является автором записи
или администратором для выполнения изменений или удаления записей.
Permission class for accessing client records.
Checks that the user is authenticated to view records.
Additionally, verifies that the user is either the author of the record
or an administrator to perform changes or deletions on records.
"""

def has_permission(self, request, view):
Expand Down
22 changes: 22 additions & 0 deletions clients/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,34 @@


class DirectorPositionSerializer(serializers.ModelSerializer[DirectorPosition]):
"""
Serializer for the DirectorPosition model.
Serializes the 'id' and 'director_position' fields of DirectorPosition.
"""

class Meta:
model = DirectorPosition
fields = ["id", "director_position"]


class ClientSerializer(serializers.ModelSerializer[Client]):
"""
Serializer for the Client model.
Serializes all fields of the Client model including nested serialization of 'director_position'.
Adds 'destination_city' and 'railway_station' as CharField serializers.
Sets the current authenticated user as the value for the 'user' field using HiddenField.
Fields:
- id: IntegerField
- director_position: Nested serialization using DirectorPositionSerializer
- destination_city: CharField for destination city name
- railway_station: CharField for railway station name
- user: HiddenField that defaults to the current authenticated user
Note: 'user' field is automatically populated with the current user making the request.
"""
director_position = DirectorPositionSerializer()
destination_city: serializers.CharField = serializers.CharField()
railway_station: serializers.CharField = serializers.CharField()
Expand Down
32 changes: 28 additions & 4 deletions clients/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,24 @@
from .serializers import ClientSerializer, DirectorPositionSerializer


# Базовый класс для получения данных по записям клиентов
class ClientAPIView(generics.ListCreateAPIView[Client]):
"""
API view for retrieving a list of clients and creating a new client record.
Retrieves a list of clients with related director position, destination city,
and railway station. Caches the client list for 15 minutes if not already cached.
"""
queryset = Client.objects.select_related(
"director_position", "destination_city", "railway_station"
).all()
serializer_class = ClientSerializer
permission_classes = (IsAuthenticated,)

def get_queryset(self):
"""
Get the queryset of clients. If cached, return cached data; otherwise, fetch from database
and cache for 15 minutes.
"""
cached_clients = cache.get("clients_list")
if cached_clients:
return cached_clients
Expand All @@ -25,22 +34,37 @@ def get_queryset(self):
return clients


# Изменение данных записи клиента
class ClientAPIUpdateView(generics.RetrieveUpdateAPIView[Client]):
"""
API view for updating a client record.
Retrieves and updates a specific client record based on its primary key.
Requires ClientAccessPermission for authorization.
"""
queryset = Client.objects.all()
serializer_class = ClientSerializer
permission_classes = (ClientAccessPermission,)


# Удаление данных записи клиента
class ClientAPIDeleteView(generics.DestroyAPIView[Client]):
"""
API view for deleting a client record.
Deletes a specific client record based on its primary key.
Requires ClientAccessPermission for authorization.
"""
queryset = Client.objects.all()
serializer_class = ClientSerializer
permission_classes = (ClientAccessPermission,)


# Передача списка позиций директора для фронтенда
class DirectorPositionListView(generics.ListAPIView[DirectorPosition]):
"""
API view for retrieving a list of director positions.
Retrieves a list of all available director positions.
Requires authentication (IsAuthenticated).
"""
queryset = DirectorPosition.objects.all()
serializer_class = DirectorPositionSerializer
permission_classes = (IsAuthenticated,)

0 comments on commit b7548c6

Please sign in to comment.