-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Slava
committed
Jun 22, 2023
1 parent
0c89218
commit a957efd
Showing
30 changed files
with
1,246 additions
and
740 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
DEBUG=True | ||
SECRET_KEY=<Your_some_long_string> | ||
ALLOWED_HOSTS=<Your_host> | ||
CSRF_TRUSTED_ORIGINS=https://<Your_host> | ||
DB_ENGINE=django.db.backends.postgresql | ||
DB_NAME=postgres | ||
POSTGRES_USER=postgres | ||
POSTGRES_PASSWORD=postgres | ||
DB_HOST=foodgram-db # Имя контейнера с БД в docker-compose.yml | ||
DB_PORT=5432 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,66 +1,77 @@ | ||
"""Модуль содержит дополнительные классы | ||
для настройки основных классов приложения. | ||
""" | ||
from core.enums import Tuples | ||
from django.db.models import Model, Q | ||
from django.db.utils import IntegrityError | ||
from django.shortcuts import get_object_or_404 | ||
from rest_framework.response import Response | ||
from rest_framework.serializers import ModelSerializer | ||
from rest_framework.status import (HTTP_201_CREATED, HTTP_204_NO_CONTENT, | ||
HTTP_400_BAD_REQUEST) | ||
from rest_framework.status import ( | ||
HTTP_201_CREATED, | ||
HTTP_204_NO_CONTENT, | ||
HTTP_400_BAD_REQUEST, | ||
) | ||
|
||
|
||
class AddDelViewMixin: | ||
""" | ||
Добавляет во Viewset дополнительные методы. | ||
Содержит метод добавляющий/удаляющий объект связи | ||
Содержит методы для добавления или удаления объекта связи | ||
Many-to-Many между моделями. | ||
Требует определения атрибута `add_serializer`. | ||
Требует определения атрибутов `add_serializer` и `link_model`. | ||
Example: | ||
class ExampleViewSet(ModelViewSet, AddDelViewMixin) | ||
... | ||
add_serializer = ExamplSerializer | ||
def example_func(self, request, **kwargs): | ||
... | ||
obj_id = ... | ||
return self.add_del_obj(obj_id, relation.M2M) | ||
link_model = M2M_Model | ||
""" | ||
|
||
add_serializer: ModelSerializer | None = None | ||
link_model: Model | None = None | ||
|
||
def _add_del_obj( | ||
self, | ||
obj_id: int | str, | ||
m2m_model: Model, | ||
q: Q | ||
) -> Response: | ||
"""Добавляет/удаляет связь M2M между пользователем и другим объектом. | ||
def _create_relation(self, obj_id: int | str) -> Response: | ||
"""Добавляет связь M2M между объектами. | ||
Args: | ||
obj_id (int | str): | ||
`id` объекта, с которым требуется создать/удалить связь. | ||
m2m_model (Model): | ||
М2M модель управляющая требуемой связью. | ||
q (Q): | ||
Условие фильтрации объектов. | ||
`id` объекта, с которым требуется создать связь. | ||
Returns: | ||
Responce: Статус подтверждающий/отклоняющий действие. | ||
""" | ||
obj = get_object_or_404(self.queryset, id=obj_id) | ||
obj = get_object_or_404(self.queryset, pk=obj_id) | ||
try: | ||
self.link_model(None, obj.pk, self.request.user.pk).save() | ||
except IntegrityError: | ||
return Response( | ||
{"error": "Действие выполнено ранее."}, | ||
status=HTTP_400_BAD_REQUEST, | ||
) | ||
|
||
serializer: ModelSerializer = self.add_serializer(obj) | ||
m2m_obj = m2m_model.objects.filter(q & Q(user=self.request.user)) | ||
return Response(serializer.data, status=HTTP_201_CREATED) | ||
|
||
if (self.request.method in Tuples.ADD_METHODS) and not m2m_obj: | ||
# Table must have: | m2m.id | obj.id(FK) | user.id(FK) | ... | | ||
m2m_model(None, obj.id, self.request.user.id).save() | ||
return Response(serializer.data, status=HTTP_201_CREATED) | ||
def _delete_relation(self, q: Q) -> Response: | ||
"""Удаляет связь M2M между объектами. | ||
if (self.request.method in Tuples.DEL_METHODS) and m2m_obj: | ||
m2m_obj[0].delete() | ||
return Response(status=HTTP_204_NO_CONTENT) | ||
Args: | ||
q (Q): | ||
Условие фильтрации объектов. | ||
Returns: | ||
Responce: Статус подтверждающий/отклоняющий действие. | ||
""" | ||
deleted, _ = ( | ||
self.link_model.objects.filter(q & Q(user=self.request.user)) | ||
.first() | ||
.delete() | ||
) | ||
if not deleted: | ||
return Response( | ||
{"error": f"{self.link_model.__name__} не существует"}, | ||
status=HTTP_400_BAD_REQUEST, | ||
) | ||
|
||
return Response(status=HTTP_400_BAD_REQUEST) | ||
return Response(status=HTTP_204_NO_CONTENT) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.