From 156dc4c34c93a9cb4a48e5ef02aab6d03c08d384 Mon Sep 17 00:00:00 2001 From: Packan Date: Fri, 1 Sep 2023 13:33:36 +0200 Subject: [PATCH] added some type hints to functions and methods :) --- backend/account/models.py | 2 +- backend/account/schema.py | 2 +- backend/account/serializers.py | 14 +++++++------- backend/account/views.py | 8 ++++---- backend/manage.py | 2 +- backend/order/cart.py | 16 ++++++++-------- backend/order/models.py | 14 +++++++------- backend/order/serializers.py | 6 +++--- backend/order/views.py | 2 +- backend/store/models.py | 34 +++++++++++++++++----------------- backend/store/schema.py | 10 +++++----- backend/store/serializers.py | 34 +++++++++++++++++----------------- backend/store/views.py | 8 ++++---- backend/vendor/models.py | 20 ++++++++++---------- backend/vendor/serializers.py | 28 ++++++++++++++-------------- backend/vendor/views.py | 14 +++++++------- 16 files changed, 107 insertions(+), 107 deletions(-) diff --git a/backend/account/models.py b/backend/account/models.py index 2bfa946..06b1412 100644 --- a/backend/account/models.py +++ b/backend/account/models.py @@ -9,7 +9,7 @@ @receiver(post_save, sender=User) -def create_or_update_vendor(sender, instance, created, **kwargs): +def create_or_update_vendor(sender, instance, created, **kwargs) -> None: print("RECEIVER") print("SENDER", sender.username) print("INSTANCE", instance) diff --git a/backend/account/schema.py b/backend/account/schema.py index fb5c7f3..b4988b2 100644 --- a/backend/account/schema.py +++ b/backend/account/schema.py @@ -17,7 +17,7 @@ class Query(graphene.ObjectType): user_details = graphene.Field(UserType) # user_details = graphene.List(UserType) - def resolve_user_details(root, info, **kwargs): + def resolve_user_details(root, info, **kwargs) -> User: """ The resolve_user_details function is a resolver function that returns the user details of the currently logged in user. It takes three arguments: root, info, and **kwargs. The root argument is required by all resolve functions and contains data about the query itself; diff --git a/backend/account/serializers.py b/backend/account/serializers.py index e97ab5e..8f127af 100644 --- a/backend/account/serializers.py +++ b/backend/account/serializers.py @@ -24,7 +24,7 @@ class Meta: fields = ["id", "username", "email", "password"] extra_kwargs = {"password": {"write_only": True}} - def create(self, validated_data): + def create(self, validated_data: dict) -> User: print("SERIALIZER") user = User.objects.create_user( validated_data["username"], @@ -42,13 +42,13 @@ class Meta: model = User fields = ("old_password", "password") - def validate_old_password(self, value): + def validate_old_password(self, value: str) -> str: user = self.context["request"].user if not user.check_password(value): raise serializers.ValidationError({"old_password": "Old password is not correct"}) return value - def update(self, instance, validated_data): + def update(self, instance, validated_data: dict) -> User: user = self.context["request"].user if user.id != instance.id: @@ -71,19 +71,19 @@ class Meta: "last_name": {"required": True}, } - def validate_email(self, value): + def validate_email(self, value: str) -> str: user = self.context["request"].user if User.objects.exclude(id=user.id).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value - def validate_username(self, value): + def validate_username(self, value: str) -> str: user = self.context["request"].user if User.objects.exclude(id=user.id).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value - def update(self, instance, validated_data): + def update(self, instance, validated_data: dict) -> User: user = self.context["request"].user if user.id != instance.id: @@ -105,7 +105,7 @@ class AccountLoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() - def validate(self, data): + def validate(self, data: dict) -> dict: user = authenticate(**data) if user and user.is_active: return user diff --git a/backend/account/views.py b/backend/account/views.py index 47f646f..4f00a04 100644 --- a/backend/account/views.py +++ b/backend/account/views.py @@ -48,7 +48,7 @@ class AccountRegisterDetailView(generics.GenericAPIView): permission_classes = (AllowAny,) @swagger_auto_schema(responses={200: user_response}) - def post(self, request, *args, **kwargs): + def post(self, request, *args, **kwargs) -> Response: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) @@ -75,7 +75,7 @@ class AccountLoginDetailView(generics.GenericAPIView): permission_classes = (AllowAny,) @swagger_auto_schema(responses={200: user_response}) - def post(self, request, *args, **kwargs): + def post(self, request, *args, **kwargs) -> Response: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data @@ -122,7 +122,7 @@ class AccountLogoutView(views.APIView): permission_classes = (IsAuthenticated,) - def post(self, request): + def post(self, request) -> Response: try: @@ -158,7 +158,7 @@ class AccountLogoutAllView(views.APIView): permission_classes = (IsAuthenticated,) - def post(self, request): + def post(self, request) -> Response: try: tokens = OutstandingToken.objects.filter(user_id=request.user.id) for token in tokens: diff --git a/backend/manage.py b/backend/manage.py index f2a662c..385e6f2 100755 --- a/backend/manage.py +++ b/backend/manage.py @@ -4,7 +4,7 @@ import sys -def main(): +def main() -> None: """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') try: diff --git a/backend/order/cart.py b/backend/order/cart.py index b07c622..b02cec5 100644 --- a/backend/order/cart.py +++ b/backend/order/cart.py @@ -3,7 +3,7 @@ from store.models import Product class Cart(object): - def __init__(self, request): + def __init__(self, request: object) -> None: self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) @@ -12,7 +12,7 @@ def __init__(self, request): self.cart = cart - def __iter__(self): + def __iter__(self) -> None: for p in self.cart.keys(): self.cart[str(p)]['product'] = Product.objects.get(pk=p) @@ -21,10 +21,10 @@ def __iter__(self): yield item - def __len__(self): + def __len__(self) -> int: return sum(item['quantity'] for item in self.cart.values()) - def add(self, product_id, quantity=1, update_quantity=False): + def add(self, product_id, quantity=1, update_quantity=False) -> None: product_id = str(product_id) if product_id not in self.cart: @@ -38,20 +38,20 @@ def add(self, product_id, quantity=1, update_quantity=False): self.save() - def remove(self, product_id): + def remove(self, product_id) -> None: if product_id in self.cart: del self.cart[product_id] self.save() - def save(self): + def save(self) -> None: self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True - def clear(self): + def clear(self) -> None: del self.session[settings.CART_SESSION_ID] self.session.modified = True - def get_total_cost(self): + def get_total_cost(self) -> float: for p in self.cart.keys(): self.cart[str(p)]['product'] = Product.objects.get(pk=p) diff --git a/backend/order/models.py b/backend/order/models.py index 27444d3..4ac9ee7 100644 --- a/backend/order/models.py +++ b/backend/order/models.py @@ -46,7 +46,7 @@ class Meta: verbose_name = _("Order") verbose_name_plural = _("Orders") - def save(self, *args, **kwargs): + def save(self, *args, **kwargs) -> None: """ If the Order instance is an immediate purchase and not an offer, set the amount to be the price of the product. @@ -62,13 +62,13 @@ def save(self, *args, **kwargs): super(Order, self).save(*args, **kwargs) - def get_price(self): + def get_price(self) -> float: return self.product.price - def get_absolute_url(self): + def get_absolute_url(self) -> str: return reverse("order:order_list", args=[self.id]) - def __str__(self): + def __str__(self) -> str: return f"Product {self.product.title} ordered by {self.buyer.name}" @@ -95,15 +95,15 @@ class Meta: verbose_name = _("Order Detail") verbose_name_plural = _("Order Details") - def get_absolute_url(self): + def get_absolute_url(self) -> str: return reverse("orderdetails:orderdetails_list", args=[self.id]) - def __str__(self): + def __str__(self) -> str: return f"Order Details of {self.full_name} on order {self.order.id}" @receiver(pre_delete, sender=Order) -def reset_product_is_available(sender, instance, **kwargs): +def reset_product_is_available(sender, instance, **kwargs) -> None: """ Reset an product's availability if an order for that product is deleted. diff --git a/backend/order/serializers.py b/backend/order/serializers.py index 7ca1da3..205fd3c 100644 --- a/backend/order/serializers.py +++ b/backend/order/serializers.py @@ -82,7 +82,7 @@ class Meta: } extra_kwargs = {"amount": {"required": False}, "order_detail": {"required": False}} - def validate(self, data): + def validate(self, data: dict) -> dict: """ Check if product is avaialable or if it is already in the buyer's orders. Ensure an offer is never more than the price of the product. @@ -112,7 +112,7 @@ def validate(self, data): return data - def create(self, validated_data): + def create(self, validated_data: dict) -> Order: request = self.context["request"] buyer = request.user.vendor # buyer = Vendor.objects.get(created_by=request.user.vendor) @@ -138,7 +138,7 @@ def create(self, validated_data): return instance - def update(self, instance, validated_data): + def update(self, instance, validated_data: dict) -> Order: user = self.context["request"].user.vendor diff --git a/backend/order/views.py b/backend/order/views.py index 203d4a6..9aef73c 100644 --- a/backend/order/views.py +++ b/backend/order/views.py @@ -100,7 +100,7 @@ class OrderItemCheckout(generics.CreateAPIView): Checkout POST. """ - def post(self, request, *args, **kwargs): + def post(self, request, *args, **kwargs) -> Response: body = request.POST.get("body") order_item = OrderModel.objects.create( product=body["product"], diff --git a/backend/store/models.py b/backend/store/models.py index 9cf5c77..37f27b1 100644 --- a/backend/store/models.py +++ b/backend/store/models.py @@ -22,11 +22,11 @@ ) -def upload_path(instance, filename): +def upload_path(instance, filename: str) -> str: return "/".join(["images", str(instance.name), filename]) -def rand_slug(): +def rand_slug() -> str: return "".join(random.choice(string.ascii_letters + string.digits) for _ in range(6)) @@ -54,15 +54,15 @@ class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") - def get_absolute_url(self): + def get_absolute_url(self) -> str: return reverse("store:category_list", args=[self.slug]) - def save(self, *args, **kwargs): + def save(self, *args, **kwargs) -> None: if not self.slug: self.slug = slugify(rand_slug() + "-" + self.name) super(Category, self).save(*args, **kwargs) - def get_slug_list(self): + def get_slug_list(self) -> list: try: ancestors = self.get_ancestors(include_self=True) except: @@ -129,20 +129,20 @@ class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") - def get_absolute_url(self): + def get_absolute_url(self) -> str: return reverse("store:product-detail", args=[self.slug]) - def save(self, *args, **kwargs): + def save(self, *args, **kwargs) -> None: if not self.slug: self.slug = slugify(self.title) super(Product, self).save(*args, **kwargs) - def __str__(self): + def __str__(self) -> str: return self.title - def __unicode__(self): + def __unicode__(self) -> str: return self.title @@ -185,23 +185,23 @@ class Meta: verbose_name_plural = _("Versatile Images") UniqueConstraint(fields=["is_feature"], condition=Q(is_feature=True), name="is_feature_is_unique") - def get_thumbnail(self): + def get_thumbnail(self) -> str: if self.image: thumbnail = self.make_thumbnail(self.image) return thumbnail else: return "https://via.placeholder.com/240x180.jpg" - def make_thumbnail(self, image, size=("240x180")): + def make_thumbnail(self, image, size=("240x180")) -> str: return image.thumbnail[size].url - def __str__(self): + def __str__(self) -> str: return self.name - def __unicode__(self): + def __unicode__(self) -> str: return self.name - def save(self, *args, **kwargs): + def save(self, *args, **kwargs) -> None: if not self.name: if self.is_feature: self.name = self.product.title + "-" + "feature" + "-" + rand_slug() @@ -215,7 +215,7 @@ def save(self, *args, **kwargs): @receiver(post_save, sender=Image) -def warm_image_instances_post_save(sender, instance, **kwargs): +def warm_image_instances_post_save(sender, instance, **kwargs) -> None: """Ensures Image objects are created post-save""" all_img_warmer = VersatileImageFieldWarmer( instance_or_queryset=instance, rendition_key_set="default_product", image_attr="image", verbose=True @@ -233,12 +233,12 @@ class Meta: verbose_name = _("Favorite Product") verbose_name_plural = _("Favorite Products") - def __str__(self): + def __str__(self) -> str: return "%s's favorites" % self.vendor.name @receiver(pre_delete, sender=Product) -def delete_category_if_null(sender, instance, **kwargs): +def delete_category_if_null(sender, instance, **kwargs) -> None: """ Delete category objects if it has no other related products. diff --git a/backend/store/schema.py b/backend/store/schema.py index a45f64c..4c66c98 100644 --- a/backend/store/schema.py +++ b/backend/store/schema.py @@ -25,7 +25,7 @@ class Meta: "updated_at", ) - def resolve_image(self, info): + def resolve_image(self, info) -> str: if self.image: self.image = info.context.build_absolute_uri(self.image.url) return self.image @@ -57,20 +57,20 @@ class Query(graphene.ObjectType): ProductType, slug=graphene.String(required=True) ) - def resolve_category_by_name(self, info, name): + def resolve_category_by_name(self, info, name) -> CategoryType: try: return Category.objects.get(name=name) except Category.DoesNotExist: return None - def resolve_all_Products_by_name(self, info, slug): + def resolve_all_Products_by_name(self, info, slug) -> ProductType: try: return Product.objects.get(slug=slug) except Product.DoesNotExist: return None - def resolve_all_Categories(self, info): + def resolve_all_Categories(self, info) -> CategoryType: return Category.objects.filter(level=1) - def resolve_all_Products(self, info): + def resolve_all_Products(self, info) -> ProductType: return Product.objects.all() diff --git a/backend/store/serializers.py b/backend/store/serializers.py index fbb7dce..859fd37 100644 --- a/backend/store/serializers.py +++ b/backend/store/serializers.py @@ -27,12 +27,12 @@ class Meta: class RawProductSlugSerializer(serializers.BaseSerializer): - def to_representation(self, obj): + def to_representation(self, obj) -> str: return obj.slug class RawIdSerializer(serializers.BaseSerializer): - def to_representation(self, obj): + def to_representation(self, obj) -> str: return obj.id @@ -57,29 +57,29 @@ class Meta: "orders_made", ] - def get_order_count(self, obj): + def get_order_count(self, obj) -> int: return order_models.Order.objects.filter(Q(vendor=obj) | Q(buyer=obj)).distinct().count() - def get_product_count(self, obj): + def get_product_count(self, obj) -> int: return Product.objects.filter(vendor=obj).count() - def get_favorites(self, obj): + def get_favorites(self, obj) -> int: favorites, created = Favorite.objects.get_or_create(vendor=obj) favorite_products = obj.favorites.favorites.all() product_serializer = RawProductSlugSerializer(favorite_products, many=True) return product_serializer.data - def get_order_requests(self, obj): + def get_order_requests(self, obj) -> int: order_requests = order_models.Order.objects.filter(vendor=obj) order_serializer = RawIdSerializer(order_requests, many=True) return order_serializer.data - def get_orders_made(self, obj): + def get_orders_made(self, obj) -> int: orders_made = order_models.Order.objects.filter(buyer=obj) order_serializer = RawIdSerializer(orders_made, many=True) return order_serializer.data - def get_product_count(self, obj): + def get_product_count(self, obj) -> int: return Product.objects.filter(vendor=obj).count() @@ -122,7 +122,7 @@ class Meta: "image": {"required": True}, } - def create(self, validated_data): + def create(self, validated_data) -> Image: instance = Image.objects.create( product=validated_data.get("product"), is_feature=validated_data.get("is_feature", False), @@ -148,7 +148,7 @@ class Meta: class RawOrderStatusSerializer(serializers.BaseSerializer): - def to_representation(self, obj): + def to_representation(self, obj) -> str: return obj.status @@ -177,7 +177,7 @@ class Meta: "product_images", ] - def get_image(self, obj): + def get_image(self, obj) -> str: images = Image.objects.filter(product=obj).first() if not images: return {} @@ -234,7 +234,7 @@ class Meta: "vendor": VendorPreviewSerializer, } - def get_image(self, obj): + def get_image(self, obj) -> str: images = Image.objects.filter(product=obj).first() if images: image_serializer = ImageNewSerializer(images) @@ -269,7 +269,7 @@ class Meta: "vendor": VendorPreviewSerializer, } - def get_image(self, obj): + def get_image(self, obj) -> str: images = Image.objects.filter(product=obj).first() if images: image_serializer = ImageNewSerializer(images) @@ -316,7 +316,7 @@ class Meta: "ordered_product": {"required": False}, } - def get_similar_products(self, obj): + def get_similar_products(self, obj) -> list: similar_products = list(obj.category.products.exclude(id=obj.id)) if len(similar_products) >= 4: @@ -325,14 +325,14 @@ def get_similar_products(self, obj): product_serializer = ProductSimilarSerializer(similar_products, many=True) return product_serializer.data - def get_image(self, obj): + def get_image(self, obj) -> str: images = Image.objects.filter(product=obj).first() if images: image_serializer = ImageNewSerializer(images) return image_serializer.data.get("image") return image_serializer.data - def create(self, validated_data): + def create(self, validated_data) -> Product: vendor = self.context["request"].user.vendor print("images field", self.context["request"].data["images"]) @@ -362,7 +362,7 @@ def create(self, validated_data): return instance - def update(self, instance, validated_data): + def update(self, instance, validated_data) -> Product: request = self.context["request"] vendor = request.user.vendor diff --git a/backend/store/views.py b/backend/store/views.py index c7ab506..7a8c02c 100644 --- a/backend/store/views.py +++ b/backend/store/views.py @@ -65,7 +65,7 @@ class ProductImagesByProductId(generics.ListAPIView): Endpoint: `api/store/images/` """ - def get_queryset(self): + def get_queryset(self) -> Image: """ The get_queryset function is used to return a QuerySet of all the images associated with the product. The get_queryset function takes in self, which represents an instance of ProductDetailView and returns a QuerySet @@ -90,7 +90,7 @@ class ProductsByVendorView(generics.ListAPIView): Endpoint: `api/store/vendor/` """ - def get_queryset(self): + def get_queryset(self) -> Product: return Product.objects.filter( vendor=Vendor.objects.get(slug=self.kwargs["slug"]) ) @@ -106,7 +106,7 @@ class ProductsByCategory(generics.ListAPIView): Endpoint: `api/store/category/` """ - def get_queryset(self): + def get_queryset(self) -> Product: """ The get_queryset function is a Django shortcut that allows you to return the queryset of objects for a given model. It takes one argument, which is the viewset class itself (in this case, it's ProductListView). @@ -137,7 +137,7 @@ class ProductsByCategories(generics.ListAPIView): products per URL arg """ - def get_queryset(self): + def get_queryset(self) -> Product: """ The get_queryset function is used to return a filtered queryset of products. It takes the kwargs from the URL as input and returns a filtered queryset. diff --git a/backend/vendor/models.py b/backend/vendor/models.py index 8685406..02768e5 100644 --- a/backend/vendor/models.py +++ b/backend/vendor/models.py @@ -16,7 +16,7 @@ ) -def upload_path(instance, filename): +def upload_path(instance, filename: str) -> str: return "/".join(["profiles", str(instance.name), filename]) @@ -41,26 +41,26 @@ class Meta: verbose_name = _("Vendor") verbose_name_plural = _("Vendors") - def __str__(self): + def __str__(self) -> str: return self.name - def __unicode__(self): + def __unicode__(self) -> str: return self.name - def get_absolute_url(self): + def get_absolute_url(self) -> str: return reverse("vendor:vendor_list", args=[self.slug]) - def get_balance(self): + def get_balance(self) -> float: items = self.items.filter(vendor_paid=False, order__vendors__in=[self.id]) return sum((item.product.price * item.quantity) for item in items) - def get_paid_amount(self): + def get_paid_amount(self) -> float: items = self.items.filter(vendor_paid=True, order__vendors__in=[self.id]) return sum((item.product.price * item.quantity) for item in items) @receiver(post_save, sender=Vendor) -def warm_vendor_image(sender, instance, **kwargs): +def warm_vendor_image(sender, instance, **kwargs) -> None: """Ensures Vendor-specific images objects are created post-save""" vendor_img_warmer = VersatileImageFieldWarmer( instance_or_queryset=instance, rendition_key_set="default_avatar", image_attr="image", verbose=True @@ -72,15 +72,15 @@ class Friend(models.Model): vendors = models.ManyToManyField(Vendor, related_name="vendors") current_vendor = models.ForeignKey(Vendor, related_name="owner", null=True, on_delete=models.CASCADE) - def __str__(self): + def __str__(self) -> str: return "%s's friends" % self.current_vendor.name @classmethod - def make_friend(cls, current_vendor, other_vendor): + def make_friend(cls, current_vendor, other_vendor) -> None: friend, created = cls.objects.get_or_create(current_vendor=current_vendor) friend.vendors.add(other_vendor) @classmethod - def lose_friend(cls, current_vendor, other_vendor): + def lose_friend(cls, current_vendor, other_vendor) -> None: friend, created = cls.objects.get_or_create(current_vendor=current_vendor) friend.vendors.remove(other_vendor) diff --git a/backend/vendor/serializers.py b/backend/vendor/serializers.py index f269602..9ce6e9a 100644 --- a/backend/vendor/serializers.py +++ b/backend/vendor/serializers.py @@ -18,7 +18,7 @@ class RawProductSlugSerializer(serializers.BaseSerializer): - def to_representation(self, obj): + def to_representation(self, obj: Product) -> str: return obj.slug @@ -71,7 +71,7 @@ class Meta: ] # extra_kwargs = {"image"} - def get_friends(self, obj): + def get_friends(self, obj: Vendor) -> list: try: friend = Friend.objects.get(current_vendor=obj) friends = friend.vendors.all() @@ -81,12 +81,12 @@ def get_friends(self, obj): friends_serializer = VendorFriendSerializer(friends, many=True) return friends_serializer.data - def get_products(self, obj): + def get_products(self, obj: Vendor) -> list: my_products = Product.objects.filter(vendor=obj.id).order_by(Lower("title")) product_serializer = ProductSerializer(my_products, many=True) return product_serializer.data - def get_friends_products(self, obj): + def get_friends_products(self, obj: Vendor) -> list: try: friend = Friend.objects.get(current_vendor=obj) friends = friend.vendors.all() @@ -97,16 +97,16 @@ def get_friends_products(self, obj): product_serializer = ProductSerializer(friends_products, many=True) return product_serializer.data - def get_favorites(self, obj): + def get_favorites(self, obj: Vendor) -> list: favorites, created = Favorite.objects.get_or_create(vendor=obj) favorite_products = obj.favorites.favorites.all() product_serializer = ProductSerializer(favorite_products, many=True) return product_serializer.data - def get_order_count(self, obj): + def get_order_count(self, obj: Vendor) -> int: return order_models.Order.objects.filter(Q(vendor=obj) | Q(buyer=obj)).distinct().count() - def get_product_count(self, obj): + def get_product_count(self, obj: Vendor) -> int: return Product.objects.filter(vendor=obj).count() @@ -150,18 +150,18 @@ class Meta: "product_count", ] - def get_products(self, obj): + def get_products(self, obj: Vendor) -> list: their_products = Product.objects.filter(vendor=obj.id).order_by(Lower("title")) product_serializer = ProductSerializer(their_products, many=True) return product_serializer.data - def get_order_count(self, obj): + def get_order_count(self, obj: Vendor) -> int: return order_models.Order.objects.filter(Q(vendor=obj) | Q(buyer=obj)).distinct().count() - def get_product_count(self, obj): + def get_product_count(self, obj: Vendor) -> int: return Product.objects.filter(vendor=obj).count() - def get_favorites(self, obj): + def get_favorites(self, obj: Vendor) -> list: favorites, created = Favorite.objects.get_or_create(vendor=obj) favorite_products = obj.favorites.favorites.all() product_serializer = ProductSerializer(favorite_products, many=True) @@ -220,13 +220,13 @@ class Meta: "slug", ] - def get_order_count(self, obj): + def get_order_count(self, obj: Vendor) -> int: return order_models.Order.objects.filter(Q(vendor=obj) | Q(buyer=obj)).distinct().count() - def get_product_count(self, obj): + def get_product_count(self, obj: Vendor) -> int: return Product.objects.filter(vendor=obj).count() - def get_favorites(self, obj): + def get_favorites(self, obj: Vendor) -> list: favorites, created = Favorite.objects.get_or_create(vendor=obj) favorite_products = obj.favorites.favorites.all() product_serializer = RawProductSlugSerializer(favorite_products, many=True) diff --git a/backend/vendor/views.py b/backend/vendor/views.py index 5f05373..4e5f604 100644 --- a/backend/vendor/views.py +++ b/backend/vendor/views.py @@ -46,7 +46,7 @@ class VendorDetailAuthView(generics.RetrieveAPIView): ] serializer_class = CurrentVendorSerializer - def get_object(self): + def get_object(self) -> Vendor: """ The get_object function is used to retrieve the object that the view will render to JSON. In this case, it returns a vendor instance based on the primary @@ -111,7 +111,7 @@ class VendorFavoriteListView(generics.ListCreateAPIView): queryset = Favorite.objects.all() permission_classes = (AllowAny,) - def get_queryset(self): + def get_queryset(self) -> list: """ The get_queryset function is used to return a QuerySet of all the favorites for a particular vendor. It takes in the id of the vendor as an argument, and then uses that id to filter through all of our @@ -128,7 +128,7 @@ def get_queryset(self): favorites_obj = get_object_or_404(self.queryset, vendor=vendor) return favorites_obj.favorites.all() - def post(self, request, id): + def post(self, request, id) -> Response: """ The post function allows the user to add a product to their favorites list. It takes in an id of a vendor and the id of a product, and adds that product @@ -152,7 +152,7 @@ def post(self, request, id): status=status.HTTP_200_OK, ) - def delete(self, request, id): + def delete(self, request, id) -> Response: """ The delete function is used to remove a product from the favorites list of a vendor. It takes in an id for the vendor and an id for the product as parameters. It then finds @@ -187,7 +187,7 @@ class VendorFriendsListView(generics.ListCreateAPIView): permission_classes = (IsAuthenticatedOrReadOnly,) queryset = Friend.objects.all() - def get_queryset(self): + def get_queryset(self) -> list: """ The get_queryset function is used to return a QuerySet of all the vendors that are friends with the vendor that owns this view. This function is called by Django when it needs to retrieve data for this view. @@ -202,7 +202,7 @@ def get_queryset(self): friends_obj = Friend.objects.get_or_create(current_vendor=vendor) return friends_obj.vendors.all() - def post(self, request, id): + def post(self, request, id) -> Response: """ The post function allows a vendor to add another vendor as a friend. It takes the id of the current vendor and the other_vendor_id, which is @@ -226,7 +226,7 @@ def post(self, request, id): status=status.HTTP_200_OK, ) - def delete(self, request, id): + def delete(self, request, id) -> Response: """ The delete function is used to remove a vendor from the friends list of another vendor. It takes in an id for the current_vendor and then removes that vendor from the other_vendor's friends list.