working on ordering products by created date

This commit is contained in:
Sam
2021-02-24 13:28:22 +00:00
parent 739c79da60
commit d98ee02f32
6 changed files with 63 additions and 8 deletions

View File

@@ -9,9 +9,9 @@ class HistorySync(models.Model):
company = models.ForeignKey('companies.Company', on_delete=models.DO_NOTHING, null=True) company = models.ForeignKey('companies.Company', on_delete=models.DO_NOTHING, null=True)
rss_url = models.URLField('URL del feed', null=True, blank=True) rss_url = models.URLField('URL del feed', null=True, blank=True)
sync_date = models.DateTimeField('Fecha de lanzamiento', null=True) sync_date = models.DateTimeField('Fecha de lanzamiento', null=True, blank=True)
result = models.TextField('Resultado', null=True, blank=True) result = models.TextField('Resultado', null=True, blank=True)
quantity = models.PositiveIntegerField('Productos importados', null=True) quantity = models.PositiveIntegerField('Productos importados', null=True, blank=True)
# internal # internal
created = models.DateTimeField('date of creation', auto_now_add=True) created = models.DateTimeField('date of creation', auto_now_add=True)

View File

@@ -33,9 +33,9 @@ class Product(models.Model):
sourcing_date = models.DateTimeField('Fecha de importación original de producto', null=True, blank=True) sourcing_date = models.DateTimeField('Fecha de importación original de producto', null=True, blank=True)
update_date = models.DateTimeField('Fecha de actualización de producto', null=True, blank=True) update_date = models.DateTimeField('Fecha de actualización de producto', null=True, blank=True)
discount = models.DecimalField('Descuento', max_digits=5, decimal_places=2, null=True, blank=True) discount = models.DecimalField('Descuento', max_digits=5, decimal_places=2, null=True, blank=True)
stock = models.PositiveIntegerField('Stock', null=True) stock = models.PositiveIntegerField('Stock', null=True, blank=True)
tags = TagField(to=TreeTag) tags = TagField(to=TreeTag)
category = SingleTagField(blank=True, null=True) # main tag category category = SingleTagField(null=True, blank=True) # main tag category
attributes = TagField(to=TreeTag, related_name='product_attributes') attributes = TagField(to=TreeTag, related_name='product_attributes')
identifiers = models.TextField('Identificador único de producto', null=True, blank=True) identifiers = models.TextField('Identificador único de producto', null=True, blank=True)

View File

@@ -163,6 +163,58 @@ class ProductViewSetTest(APITestCase):
# Assert number of instnaces in response # Assert number of instnaces in response
self.assertEquals(len(expected_instance), len(payload)) self.assertEquals(len(expected_instance), len(payload))
def test_anon_user_can_filter_company(self):
# create instances
company = CompanyFactory()
expected_instance = [
self.factory(category='ropa', tags="zapatos, rojos", company=company),
self.factory(category='ropa', tags="rojos", company=company),
self.factory(category='ropa', tags="colores/rojos", company=company)
]
unexpected_instance = [
self.factory(category='roperos', tags="zapatos, azules"),
self.factory(category='enropados', tags="xxl")
]
# prepare url
url = f"{self.endpoint}?company={company.id}"
# Request list
response = self.client.get(url)
payload = response.json()
# Assert access is granted
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Assert number of instnaces in response
self.assertEquals(len(expected_instance), len(payload))
def test_anon_user_can_order_products(self):
# create instances
company = CompanyFactory()
unexpected_instance = [
self.factory(category='roperos', tags="zapatos, azules"),
self.factory(category='enropados', tags="xxl")
]
expected_instance = [
self.factory(category='ropa', tags="zapatos, rojos", company=company),
self.factory(category='ropa', tags="rojos", company=company),
self.factory(category='ropa', tags="colores/rojos", company=company)
]
# prepare url
url = f"{self.endpoint}?ordering=created"
# Request list
response = self.client.get(url)
payload = response.json()
# Assert access is granted
self.assertEqual(response.status_code, status.HTTP_200_OK)
# TODO: assert correct order
previous_date = datetime.datetime.now()
for instance in payload:
self.assertTrue(datetime.datetime.fromisoformat(instance['created'][:-1]) < previous_date)
previous_date = datetime.datetime.fromisoformat(instance['created'][:-1])
# authenticated user # authenticated user
def test_auth_user_can_list_instances(self): def test_auth_user_can_list_instances(self):
"""Regular logged-in user can list instance """Regular logged-in user can list instance

View File

@@ -15,6 +15,7 @@ from rest_framework import viewsets
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAdminUser, IsAuthenticated from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAdminUser, IsAuthenticated
from rest_framework.decorators import api_view, permission_classes, action from rest_framework.decorators import api_view, permission_classes, action
from rest_framework.filters import OrderingFilter
import requests import requests
@@ -41,6 +42,8 @@ class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all() queryset = Product.objects.all()
serializer_class = ProductSerializer serializer_class = ProductSerializer
permission_classes = [IsAuthenticatedOrReadOnly, IsCreator] permission_classes = [IsAuthenticatedOrReadOnly, IsCreator]
# filter_backends = [ProductTagFilter, OrderingFilter]
# ordering_fields = ['created']
filterset_class = ProductTagFilter filterset_class = ProductTagFilter
filterset_fields = ['name', 'tags', 'category', 'attributes', 'company', 'created'] filterset_fields = ['name', 'tags', 'category', 'attributes', 'company', 'created']

View File

@@ -17,11 +17,11 @@ class StatsLog(models.Model):
action_object_object_id = models.CharField(max_length=255, blank=True, null=True) action_object_object_id = models.CharField(max_length=255, blank=True, null=True)
action_object = GenericForeignKey('action_object_content_type', 'action_object_object_id') action_object = GenericForeignKey('action_object_content_type', 'action_object_object_id')
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True)
anonymous = models.BooleanField('Usuario no registrado', null=True) anonymous = models.BooleanField('Usuario no registrado', null=True, blank=True)
ip_address = models.GenericIPAddressField('IP usuario', null=True, blank=True) ip_address = models.GenericIPAddressField('IP usuario', null=True, blank=True)
geo = models.PointField('Ubicación aproximada', null=True, blank=True ) geo = models.PointField('Ubicación aproximada', null=True, blank=True )
contact = models.BooleanField('Empresa contactada', null=True) contact = models.BooleanField('Empresa contactada', null=True, blank=True)
shop = models.BooleanField('Redirigido por botón "Comprar"', null=True) shop = models.BooleanField('Redirigido por botón "Comprar"', null=True, blank=True)
# internal # internal
created = models.DateTimeField('date of creation', auto_now_add=True) created = models.DateTimeField('date of creation', auto_now_add=True)

View File

@@ -26,7 +26,7 @@ class ProductTagFilter(django_filters.FilterSet):
class Meta: class Meta:
model = Product model = Product
fields = ['name', 'tags', 'category', 'attributes'] fields = ['name', 'tags', 'category', 'attributes', 'company', 'created']
def tag_filter(self, queryset, name, value): def tag_filter(self, queryset, name, value):
return queryset.filter(**{ return queryset.filter(**{