def __init__(self, *args, **kwargs): kwargs.setdefault('editable', True) kwargs.setdefault('max_digits', 5) kwargs.setdefault('decimal_places', 2) kwargs.setdefault( 'help_text', _('Report in kg. Format is 9.99, 99.99, etc')) DecimalField.__init__(self, *args, **kwargs)
def test_transform(self): try: DecimalField.register_lookup(ACos) DecimalModel.objects.create(n1=Decimal('0.5'), n2=Decimal('0')) DecimalModel.objects.create(n1=Decimal('-0.9'), n2=Decimal('0')) objs = DecimalModel.objects.filter(n1__acos__lt=2) self.assertQuerysetEqual(objs, [Decimal('0.5')], lambda a: a.n1) finally: DecimalField._unregister_lookup(ACos)
def test_transform(self): try: DecimalField.register_lookup(Ceil) DecimalModel.objects.create(n1=Decimal('3.12'), n2=Decimal('0')) DecimalModel.objects.create(n1=Decimal('1.25'), n2=Decimal('0')) objs = DecimalModel.objects.filter(n1__ceil__gt=3) self.assertQuerysetEqual(objs, [Decimal('3.12')], lambda a: a.n1) finally: DecimalField._unregister_lookup(Ceil)
def test_transform(self): try: DecimalField.register_lookup(Floor) DecimalModel.objects.create(n1=Decimal('5.4'), n2=Decimal('0')) DecimalModel.objects.create(n1=Decimal('3.4'), n2=Decimal('0')) objs = DecimalModel.objects.filter(n1__floor__gt=4) self.assertQuerysetEqual(objs, [Decimal('5.4')], lambda a: a.n1) finally: DecimalField._unregister_lookup(Floor)
def test_transform(self): try: DecimalField.register_lookup(Round) DecimalModel.objects.create(n1=Decimal('2.0'), n2=Decimal('0')) DecimalModel.objects.create(n1=Decimal('-1.0'), n2=Decimal('0')) objs = DecimalModel.objects.filter(n1__round__gt=0) self.assertQuerysetEqual(objs, [Decimal('2.0')], lambda a: a.n1) finally: DecimalField._unregister_lookup(Round)
class IncidentDetail(models.Model): class Meta: db_table = 'monitor_incident_details' ordering = ['-created_dttm'] incident = ForeignKey(Incident, on_delete=deletion.CASCADE, null=False) cur_value = DecimalField(null=False, max_digits=6, decimal_places=2, default=0) min_value = DecimalField(null=False, max_digits=6, decimal_places=2, default=0) max_value = DecimalField(null=False, max_digits=6, decimal_places=2, default=0) cur_test_w_values = CharField(max_length=500, null=False, default='') max_status = CharField(max_length=15, null=False, choices=Incident.StatusChoices.choices, default=Incident.StatusChoices.WATCHING) pending_status = CharField(max_length=15, null=False, choices=Incident.StatusChoices.choices, default=Incident.StatusChoices.WATCHING) current_status = CharField(max_length=15, null=False, choices=Incident.StatusChoices.choices, default=Incident.StatusChoices.WATCHING) critical_ticks = IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)], null=False, default=0) warning_ticks = IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)], null=False, default=0) normal_ticks = IntegerField(validators=[MinValueValidator(0), MaxValueValidator(3)], null=False, default=0) created_dttm = DateTimeField(editable=False, auto_now_add=True)
class Map(TimeStampedModel): game = ForeignKey(Game, null=False) radius = DecimalField(max_digits=10, decimal_places=4, null=True, blank=True) height = DecimalField(max_digits=10, decimal_places=4, null=True, blank=True) width = DecimalField(max_digits=10, decimal_places=4, null=True, blank=True) side = DecimalField(max_digits=10, decimal_places=4, null=True, blank=True) rows = IntegerField(null=True, blank=True) columns = IntegerField(null=True, blank=True)
def get_test_price(self): return Orders.objects.filter(pk=self.pk).values( 'order_items__test__id', 'order_items__test__test_group__name', 'order_items__test__name', 'order_items__test__test_price__tariff').annotate( sub_total=ExpressionWrapper( F('order_items__test__test_price__tariff'), output_field=DecimalField(decimal_places=2)))
def sum_cost(self): total_cost = self.aggregate(total_cost=models.Sum(F("quantity") * F("product_price"), output_field=DecimalField(decimal_places=2))).get( "total_cost") if total_cost is not None: return total_cost else: return Decimal('0')
def get_subtotal_discount(self): subtotal_discount = OrderItem.objects.filter( order_item=self, allowable=True).aggregate(subtotal_applied_discount=Sum( "applied_discount", field="applied_discount * count", output_field=DecimalField()))['subtotal_applied_discount'] or 0 return self.count * (float(subtotal_discount) + self.applied_discount)
def get_subtotal_wt(self): subitemtotal_wt = OrderItem.objects.filter( order_item=self, allowable=True).aggregate(subtotal_wt=Sum( F("price_discounted_wt") * F("count"), field="price_discounted_wt ", output_field=DecimalField()))['subtotal_wt'] or 0 return self.count * (round(subitemtotal_wt) + round(self.price_discounted_wt))
class BudgetField(Model): code = CharField(max_length=16) title = CharField(max_length=256) amount = DecimalField(max_digits=10, decimal_places=2) budget = ForeignKey('Budget', on_delete=CASCADE) class Meta: db_table = 'budget_fields'
class BarometricData(Model): instrument = ForeignKey('Instrument', related_name='barometric_instrument', on_delete=models.CASCADE) time = OneToOneField('TimeData', related_name='barometric_time', on_delete=models.CASCADE) Barometric = DecimalField(decimal_places=3, max_digits=20, null=True)
class TemperatureData(Model): instrument = ForeignKey('Instrument', related_name='temperature_instrument', on_delete=models.CASCADE) time = OneToOneField('TimeData', related_name='temperature_time', on_delete=models.CASCADE) temperature = DecimalField(decimal_places=3, max_digits=20, null=True)
def test_summary_timed_total(self): #For the oldest time, total consumption for all the users would be 90*15 total_summary = Usage.objects.values('timestamp') \ .annotate(total_usage=Sum('consumption'), \ avg_usage=Avg('consumption',output_field=DecimalField(max_digits=10, decimal_places=1))) \ .order_by('timestamp') oldest_total_usage = total_summary[0]['total_usage'] self.assertEqual(oldest_total_usage, 1350)
def get_queryset(self): return PuntoVentaTurnoQuerySet(self.model, using=self._db).select_related( 'punto_venta' ).annotate( total_efectivo=ExpressionWrapper( Sum('transacciones_caja__valor_efectivo'), output_field=DecimalField(max_digits=12, decimal_places=2) ), total_tarjeta=ExpressionWrapper( Sum('transacciones_caja__valor_tarjeta'), output_field=DecimalField(max_digits=12, decimal_places=2) ), total_tarjeta_cantidad=ExpressionWrapper( Sum('transacciones_caja__nro_vauchers'), output_field=IntegerField() ) ).all()
class VehicleType(Model): """From a VehicleType any number of vehicles can be created. VehicleType defines the "static" costs of a Vehicle, while the Vehicles class contains the parameters of the instance """ name = CharField(max_length=127, unique=True) vocal_name = CharField(max_length=255, blank=True) workshop_category = ForeignKey(WorkshopCategory, on_delete=PROTECT) v_max = IntegerField() total_price = DecimalField(max_digits=12, decimal_places=2) cost_per_km = DecimalField(max_digits=12, decimal_places=6) cost_per_hour = DecimalField(max_digits=12, decimal_places=6) multi_head_limit = IntegerField() cargo_tons_limit = IntegerField() def __str__(self): if self.vocal_name != "": return f"{self.name} ({self.vocal_name})" return f"{self.name}"
class Charge(Model): value = DecimalField(max_digits=8, decimal_places=2) transactedAt = DateTimeField(default=datetime.today) account = ForeignKey(Account) def __str__(self): return "( " + str(self.transactedAt) + " )" + " " + str( self.value) + " -> " + str(self.account)
class ReportedEntry(Model): company = ForeignKey('Company') year = IntegerField() name = CharField(max_length=256) value = DecimalField(decimal_places=5, max_digits=20) statement = CharField(max_length=256, blank=True) unique_together = ("company", "year", "name")
class Alphabet(Model): a = IntegerField(default=1) b = IntegerField(default=2) c = IntegerField(default=3) d = CharField(max_length=32) e = CharField(max_length=32, null=True) f = IntegerField(null=True) g = DecimalField(default=0, decimal_places=2, max_digits=10)
class KeyDecimalTransform(KeyTextTransform): """Return a decimal for our numeric JSON.""" output_field = DecimalField() def as_postgresql(self, compiler, connection): sqlpart, params = super().as_postgresql(compiler, connection) return sqlpart + "::numeric", params
class Payment(Model): user_profile = ForeignKey(UserProfile, on_delete=CASCADE, null=False) shelter = ForeignKey(Shelter, on_delete=CASCADE, null=False) amount = DecimalField(max_digits=15, decimal_places=2) def __str__(self): return 'Payment: {} from {} to {}'.format(self.amount, self.user_profile, self.shelter)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) items = ShoppingCartItem.objects.get_items(self.object) context['is_cart_empty'] = (items.count() == 0) order = items.aggregate(total_order=Sum( F('price_per_unit') * F('quantity'), output_field=DecimalField())) context['total_order'] = order['total_order'] return context
def _get_total_received(self): return Coalesce( Case(When( user_id=F('registration__consultant_id'), then=self._get_case_equal_commission_user_and_consultant()), default=self. _get_case_non_equal_commission_user_and_consultant(), output_field=DecimalField()), 0)
def _get_case_non_equal_commission_user_and_consultant(self): return Case( When(registration__registrationfinance__deposit_received__gte=F( 'registration__registrationfinance__commission_received'), then=Value(0)), default=F('registration__registrationfinance__commission_received') * F('percentage') * Decimal('0.01'), output_field=DecimalField())
class Weapon(Model): weapon_type = FK(to=WeaponType, related_name='weapons', on_delete=PROTECT) name = CharField(max_length=100, unique=True) description = TextField(max_length=4000, blank=True, null=True) picture_sets = M2M(to=PictureSet, related_name='weapons', blank=True) # -------------------# TODO marked for removal [in 2023]------------------- delay = PositiveSmallIntegerField() damage_big_dices = CharField(max_length=10, blank=True, null=True) damage_big_add = PositiveSmallIntegerField(blank=True, null=True) # ------------------------------------------------------------------------- damage_small_dices = CharField(max_length=10, blank=True, null=True) damage_small_add = PositiveSmallIntegerField(blank=True, null=True) damage_type = CharField(max_length=10, choices=DAMAGE_TYPES) special = TextField(max_length=4000, blank=True, null=True) range = CharField(max_length=100, blank=True, null=True) size = CharField(max_length=5, choices=SIZES) trait = CharField(max_length=10, choices=TRAITS) avg_price_value = PositiveSmallIntegerField(blank=True, null=True) avg_price_currency = CharField(max_length=5, choices=CURRENCIES, blank=True, null=True) avg_weight = DecimalField(max_digits=10, decimal_places=1) allowed_profiles = M2M( to=Profile, limit_choices_to=Q(status='player'), related_name='allowed_weapons', blank=True, ) sorting_name = CharField(max_length=250, blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if self.name: self.sorting_name = create_sorting_name(self.name) super().save(*args, **kwargs) def short_name(self): return rid_of_special_chars(self.name) def damage_summary(self): damage_small = str(self.damage_small_dices) # if self.damage_small_add: # damage_small += ('+' + str(self.damage_small_add)) # damage_big = str(self.damage_big_dices) # if self.damage_big_add: # damage_big += ('+' + str(self.damage_big_add)) damage_small_add = "" if self.damage_small_add: damage_small_add += ("+" + str(self.damage_small_add)) return f"{self.damage_small_dices}{damage_small_add}" class Meta: ordering = ['sorting_name']
def handle(self, *args, **options): action_1__time_delta = timedelta(hours=12) action_2__time_delta = timedelta(days=1) action_1__discount = 0.3 action_2__discount = 0.15 action_expired__discount = 0.05 # условие: заказ был сделан менее 12 часов назад action_1__condition = Q(order__updated__lte=F('order__created') + action_1__time_delta) # условие: заказ был сделан более 12 часов назад, но менее 1 дня назад action_2__condition = Q(order__updated__gt=F('order__created') + action_1__time_delta) & \ Q(order__updated__lte=F('order__created') + action_2__time_delta) # условие: заказ был сделан более 1 дня назад action_expired__condition = Q(order__updated__gt=F('order__created') + action_2__time_delta) # если заказ новый, то 1 action_1__order = When(action_1__condition, then=1) # если заказ постарше, то 2 action_2__order = When(action_2__condition, then=2) # если заказ старый (более суток), то 3 action_expired__order = When(action_expired__condition, then=3) # скидка меняется от времени заказа # на свежие заказы скидка 30% - 0,3 action_1__price = When(action_1__condition, then=F('product__price') * F('quantity') * action_1__discount) # скидка 15% - 0,15 action_2__price = When(action_2__condition, then=F('product__price') * F('quantity') * action_2__discount) # скидка 5% - 0,05 action_expired__price = When(action_expired__condition, then=F('product__price') * F('quantity') * action_expired__discount) test_orderss = OrderItem.objects.annotate(action_order=Case( action_1__order, action_2__order, action_expired__order, output_field=IntegerField(), # тип результата )).annotate(total_price=Case( action_1__price, action_2__price, action_expired__price, output_field=DecimalField(), # тип результата )).order_by('action_order', 'total_price').select_related() # категория заказа: 1, 2, 3 # total_price - вычисляется в зависимости от скидки for orderitem in test_orderss: print(f'{orderitem.action_order:2}: заказ №{orderitem.pk:3}:\ {orderitem.product.name:15}: скидка\ {abs(orderitem.total_price):6.2f} руб. | \ {orderitem.order.updated - orderitem.order.created}')
def _populate_daily_summary_table(self): """Populate the daily summary table.""" included_fields = [ 'usage_start', 'usage_end', 'namespace', 'pod', 'node', 'cluster_id', 'node_capacity_cpu_cores', 'pod_labels', ] annotations = { 'pod_usage_cpu_core_hours': F('pod_usage_cpu_core_seconds') / 3600, 'pod_request_cpu_core_hours': Sum( ExpressionWrapper( F('pod_request_cpu_core_seconds') / 3600, output_field=DecimalField() ) ), 'pod_limit_cpu_core_hours': Sum( ExpressionWrapper( F('pod_limit_cpu_core_seconds') / 3600, output_field=DecimalField() ) ), 'pod_usage_memory_gigabyte_hours': Sum( ExpressionWrapper( F('pod_usage_memory_byte_seconds') / 3600, output_field=DecimalField() ) ) * 1e-9, 'pod_request_memory_gigabyte_hours': Sum( ExpressionWrapper( F('pod_request_memory_byte_seconds') / 3600, output_field=DecimalField() ) ) * 1e-9, 'pod_limit_memory_gigabyte_hours': ExpressionWrapper( F('pod_limit_memory_byte_seconds') / 3600, output_field=DecimalField() ) * 1e-9, 'node_capacity_cpu_core_hours': F('node_capacity_cpu_core_seconds') / 3600, 'node_capacity_memory_gigabytes': F('node_capacity_memory_bytes') * 1e-9, 'node_capacity_memory_gigabyte_hours': ExpressionWrapper( F('node_capacity_memory_byte_seconds') / 3600, output_field=DecimalField() ) * 1e-9, 'cluster_capacity_cpu_core_hours': F('cluster_capacity_cpu_core_seconds') / 3600, 'cluster_capacity_memory_gigabyte_hours': ExpressionWrapper( F('cluster_capacity_memory_byte_seconds') / 3600, output_field=DecimalField() ) * 1e-9, } entries = OCPUsageLineItemDaily.objects.values(*included_fields).annotate(**annotations) for entry in entries: summary = OCPUsageLineItemDailySummary(**entry) summary.save()
class Server(Model): class Meta: db_table="dbaas_server" def __str__(self): return self.server_name class NodeRoleChoices(DjangoChoices): CONFIGURING = ChoiceItem("Configuring", "Primary Configuring", 1) PRIMARY = ChoiceItem("Primary", "Primary Node", 2) SECONDARYSYNC = ChoiceItem("SecondarySync", "Secondary Node - Replication is Synchronous", 3) SECONDARYASYNC = ChoiceItem("SecondaryAsync", "Secondary Node- Replication is Asynchronous", 4) ARBITER = ChoiceItem("Arbiter", "Arbiter Node", 5) POOLSERVER = ChoiceItem("PoolServer", "PoolServer", 6) POOLSERVERLOCKED = ChoiceItem("PoolServerLocked", "PoolServerLocked", 7) class ServerHealthChoices(DjangoChoices): SERVERCONFIGURING = ChoiceItem("ServerConfig", "Server Configuring", 1) SERVERUP = ChoiceItem("ServerUp", "Server Up and Healthy", 2) SERVERUPWITHISSUES = ChoiceItem("ServerUpWithIssues", "Server is Up but something is Not Healthy", 3) SERVERDOWN = ChoiceItem("ServerDown", "Server is Down", 4) SERVERONLINEMAINT = ChoiceItem("ServerOnLineMaint", "Server On-Line Maintenance", 5) cluster = ForeignKey(Cluster, related_name='clusters', on_delete=deletion.CASCADE, null=True, blank=True) environment = ForeignKey(Environment, on_delete=deletion.CASCADE, null=True, blank=True) server_name = CharField(max_length=30, null=False, unique=True) server_ip = CharField(max_length=14, null=True, blank=True) cpu = DecimalField(decimal_places=1, max_digits=3, null=True, blank=True) ram_gb = DecimalField(decimal_places=1, max_digits=3, null=True, blank=True) db_gb = DecimalField(decimal_places=2, max_digits=5, null=True, blank=True) datacenter = ForeignKey(Datacenter, on_delete=deletion.CASCADE, null=True, blank=True) node_role = CharField(choices=NodeRoleChoices.choices, max_length=20, null=False, default='') server_health = CharField(choices=ServerHealthChoices.choices, max_length=20, null=True, blank=True) last_reboot = DateTimeField(null=True, blank=True) dbms_type = CharField(choices=DbmsTypeChoices.choices, max_length=20, null=True, blank=True) os_version = CharField(max_length=30, null=True, blank=True) os_patched_dttm = DateTimeField(null=True, blank=True) db_version = CharField(max_length=30, null=True, blank=True) db_version_number = IntegerField(validators=[MinValueValidator(0)], null=True, blank=True) db_patched_dttm = DateTimeField(null=True, blank=True) pending_restart_sw = BooleanField(null=False, default=False) metrics_sw = BooleanField(null=False, default=True) active_sw = BooleanField(null=False, default=True) created_dttm = DateTimeField(editable=False, auto_now_add=True, null=False) updated_dttm = DateTimeField(auto_now=True, null=False)
def get(self, request, *args, **kwargs): # The Liquidity states where the company has invested its money # and how much he holds in reverse. # # Currently, there are 3 multi-options: # - Company has cash # - Company has bonds # - Company has invested in shares/stocks # # Hence, we need to retrieve data from 3 different tables. isin = self.kwargs["isin"] company = (Company.objects.only( "cash", "isin").filter(isin=isin).annotate( bond_value=Coalesce( Subquery( Bond.objects.filter(company_id=OuterRef("id")).values( "company_id").annotate( s=Sum("value")).values("s")[:1], output_field=DecimalField(), ), 0, ), depot_value=Coalesce( Subquery( DepotPosition.objects.add_value().filter( depot_of_id=OuterRef("id")).values("depot_of_id"). annotate(s=Sum("value")).values("s")[:1], output_field=DecimalField(), ), 0, ), ).values("cash", "bond_value", "depot_value")) company = company.first() if not company: raise Http404 data = { "cash": company["cash"], "bonds": company["bond_value"], "depot_value": company["depot_value"] } return Response(data=data)
def get_queryset(self): place_qs = WinterStoragePlace.objects.filter( winter_storage_section=OuterRef("pk")) dimension_qs = _get_dimensions_qs( place_qs, place_type_name="place_type", section_name="winter_storage_section", ) # When annotating the count, if no elements match the filter, the whole queryset will # return an empty QuerySet<[]>, which will then return None as value for the count. # # By adding the other annotate with Coalesce, we ensure that, we'll always get an int value available_places = (place_qs.filter( is_available=True, is_active=True ).order_by().values("winter_storage_section").annotate( nullable_count=Count("*")).values("nullable_count").annotate( count=Coalesce("nullable_count", Value(0))).values("count")) inactive_places = (place_qs.filter(Q(is_active=False)).order_by( ).values("winter_storage_section").annotate( nullable_count=Count("*")).values("nullable_count").annotate( count=Coalesce("nullable_count", Value(0))).values("count")) all_places = ( place_qs.order_by().values("winter_storage_section").annotate( count=Count("*")).values("count")) return (super().get_queryset().annotate( max_width=Subquery( dimension_qs("width"), output_field=DecimalField(), ), max_length=Subquery( dimension_qs("length"), output_field=DecimalField(), ), number_of_places=Subquery(all_places, output_field=PositiveIntegerField()), number_of_free_places=Subquery( available_places, output_field=PositiveIntegerField()), number_of_inactive_places=Subquery( inactive_places, output_field=PositiveIntegerField(), ), ))
def awarded_bonuses_available_for_cash_in(player): return AwardedBonus.objects.filter( player=player, cashed_in=False, bonus__awards_real_money=False, ).annotate(wagering_amount=ExpressionWrapper( F('amount') * F('bonus__wagering_requirement'), output_field=DecimalField()), ).filter( wagering_amount__lte=player.money_spent_toward_bonus, )
def test_max_length(self): field = DecimalField(name='thestring', max_digits=5, decimal_places=2) field_model = FieldModel.from_django(field) option = field_model.options[2] self.assertEqual(option.name, 'max_digits') self.assertEqual(option.value, '5') option = field_model.options[1] self.assertEqual(option.name, 'decimal_places') self.assertEqual(option.value, '2')
class ProductPromotion(Model): product = OneToOneField(Product, on_delete=CASCADE) price = DecimalField(max_digits=6, decimal_places=2) @property def percentage_of_the_promotion(self): value_in_percents = round((self.product.price / self.price) * 10) return value_in_percents @property def name(self): name = self.product return name @property def availability(self): availability = self.product.availability return availability @property def category(self): category = self.product.meta_product.category return category @property def description(self): description = self.product.meta_product.description return description @property def digital(self): digital = self.product return digital @property def imageURL(self): image = self.product.meta_product.image if image: url = self.product.meta_product.image.url else: url = '' return url @property def measure(self): measure = self.product.measure return measure @property def package(self): package = self.product.package return package @property def standard_price(self): standard_price = self.product.price return standard_price
class SchoolLocation(Model): ''' Stores information on the region, district, and zone that a specific school is located in. Relates :model:`api.School`, :model:`api.Region`, :model:`api.District`, and :model:`api.Zone`. ''' school = ForeignKey(School) region = ForeignKey(Region) district = ForeignKey(District) zone = ForeignKey(Zone) latitude = DecimalField(max_digits=13, decimal_places=10, default=-6.3690) longitude = DecimalField(max_digits=13, decimal_places=10, default=34.8888) def __str__(self): return self.school