class Collector(models.Model): key = models.UUIDField(default=uuid.uuid4, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="collectors", null=True) latitude = DecimalField(max_digits=20, decimal_places=10, default=0.0) longitude = DecimalField(max_digits=20, decimal_places=10, default=0.0) timestamp = BigIntegerField(default=0) timestampData = BigIntegerField(default=0) def getDate(self): return datetime.datetime.fromtimestamp(int( self.timestamp / 1000)).strftime('%d/%m/%Y %H:%M:%S') def getStrLatitude(self): return "%.8f" % self.latitude def getStrLongitude(self): return "%.8f" % self.longitude def __unicode__(self): return "Active collector from " + self.user.username
class AboForm(Form): anteilscheine = CharField(label='asdf', min_length=1) anteilscheine_added = DecimalField(max_digits=2, decimal_places=0) small_abos = DecimalField(max_digits=2, decimal_places=0) big_abos = DecimalField(max_digits=2, decimal_places=0) house_abos = DecimalField(max_digits=2, decimal_places=0) depot = CharField(widget=Select)
class CompanyChartsViewSet(GenericViewSet, ListModelMixin): queryset = Company.objects.annotate(__session_average=Subquery( Session.objects.filter(company=OuterRef("id")).annotate( value=ExpressionWrapper(Avg("answered_questions__value") * F("set__weight"), output_field=DecimalField( max_digits=3, decimal_places=2, ))).values("value"))).annotate( date=Case( When(sessions__until__lte=Now(), then=F("sessions__until")), default=Now()), data=ExpressionWrapper( Sum("__session_average") * F("sessions__theme__weight"), output_field=DecimalField( decimal_places=2, max_digits=3))).values( "data", "date") serializer_class = CompanyChartSerializer def filter_queryset(self, queryset): return queryset.filter(id=self.request.user.member.company_id)
class Order(models.Model): """ An order that has been placed after purchasing courses. """ subtotal = DecimalField(decimal_places=2, max_digits=20) total_paid = DecimalField(decimal_places=2, max_digits=20) purchaser = ForeignKey(User) created_at = DateTimeField(auto_now_add=True, blank=True) modified_at = DateTimeField(auto_now=True, blank=True)
def allocations_waiting(request): short_allocations = {} over_allocations = {} for space in Space.objects.all(): requested = Allocation.objects \ .filter(artist=OuterRef('artistid'), space=space) \ .annotate(sum=Sum('requested')).values('sum') artist_1_allocated = Location.objects \ .filter(artist_1=OuterRef('artistid'), type=space) \ .values('artist_1__pk') \ .annotate(sum=Sum(Case(When(Q(half_space=True) | Q(space_is_split=True), then=V(0.5)), default=V(1), output_field=DecimalField()))) \ .values('sum') artist_2_allocated = Location.objects \ .filter(artist_2=OuterRef('artistid'), type=space) \ .values('artist_2__pk') \ .annotate(sum=Sum(Case(When(Q(half_space=True) | Q(space_is_split=True), then=V(0.5)), default=V(1), output_field=DecimalField()))) \ .values('sum') artists = Artist.objects.annotate( requested=Subquery(requested), artist_1_allocated=Subquery(artist_1_allocated), artist_2_allocated=Subquery(artist_2_allocated)) for artist in artists: if artist.requested is None: artist.requested = Decimal(0) artist.allocated = (artist.artist_1_allocated or Decimal(0)) + \ (artist.artist_2_allocated or Decimal(0)) map = None if artist.allocated > artist.requested: map = over_allocations elif artist.allocated < artist.requested: map = short_allocations else: continue space_artists = map.setdefault(space.name, []) space_artists.append({ 'artistid': artist.artistid, 'artist': str(artist), 'requested': artist.requested, 'allocated': artist.allocated, }) sections = [ ('Short Allocations', short_allocations), ('Over Allocations', over_allocations), ] return render(request, 'artshow/allocations_waiting.html', {'sections': sections})
class OrderLine(models.Model): """ A module which is purchased. """ order = ForeignKey(Order) seats = IntegerField() module = ForeignKey(Module) price_without_tax = DecimalField(decimal_places=2, max_digits=20) line_total = DecimalField(decimal_places=2, max_digits=20) created_at = DateTimeField(auto_now_add=True, blank=True) modified_at = DateTimeField(auto_now=True, blank=True)
def copy_fields(model): """ Creates copies of the model's original fields, returning a dictionary mapping field name to copied field object. """ fields = { PK: AutoField(verbose_name=PK, primary_key=True, auto_created=True), CU: create_user_field(CU), DU: create_user_field(DU), VF: DecimalField(max_digits=18, decimal_places=6, default=0, auto_created=True), VU: DecimalField(max_digits=18, decimal_places=6, default=MAX, auto_created=True)} for field in model._meta.local_fields: if field.name in FORBIDDEN_FIELDS: raise Exception('Can not use `%s` as a field name ' 'with django-timetravel') _field = get_non_related(field) _field.primary_key = field.primary_key if isinstance(_field, AutoField): _field = auto_to_integer(field) _field._tt_field_attrname = field.attname _field._tt_field_name = field.name if not isinstance(_field, BooleanField): _field.null = True if _field.primary_key: _field.primary_key = False _field.serialize = True _field.name = OK _field.db_index = True _field.null = False _field.db_column = field.db_column or field.attname _field._unique = False _field.unique_for_date = False if _field.unique_for_date else None _field.unique_for_month = False if _field.unique_for_month else None _field.unique_for_year = False if _field.unique_for_year else None _field.auto_now = False _field.auto_now_add = False _field.auto_created = False fields[_field.name] = _field return fields
class Product(models.Model): name = models.CharField(max_length=25) price = DecimalField(max_digits=10, decimal_places=2) created_at = DateTimeField(auto_created=True, auto_now=True) def __str__(self) -> str: return self.name + "_" + str(self.created_at)
class Bond(models.Model): isin = CharField(max_length=12) size = DecimalField(max_digits=20, decimal_places=3) currency = CharField(max_length=3) maturity = DateField() lei = CharField(max_length=20) legal_name = CharField(max_length=128, blank=True, null=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __repr__(self): return f'Bond ({self.isin})' @classmethod def get_legal_name_from_gleif(cls, lei: str) -> Optional[str]: try: logging.info(f"Getting legal name for LEI {lei} from GLEIF's API") r = requests.get( f'https://leilookup.gleif.org/api/v2/leirecords?lei={lei}') r.raise_for_status() legal_name = r.json()[0]['Entity']['LegalName']['$'] except Exception as ex: logging.exception( f'Could not fetch legal name of bond (LEI={lei}) from GLEIF API: {ex}' ) legal_name = None return legal_name
class MetaData(Model): """This model provide a type's option and the actual weight.""" option = CharField(max_length=255) weight = DecimalField(default=1, max_digits=3, decimal_places=1) meta_type = ForeignKey(MetaType, CASCADE, "options")
class Order(AbstractUUIDModel): author = models.ForeignKey( Account, on_delete=models.CASCADE, editable=False, null=False ) executor = models.OneToOneField( Account, null=True, editable=False, on_delete=models.SET_NULL, related_name='current_order' ) title = models.CharField( max_length=100, blank=False, null=False, unique=True) description = models.TextField(blank=False, null=False) date_posted = models.DateTimeField(auto_now_add=True) price = DecimalField( default=Decimal('5.00'), max_digits=6, decimal_places=2, null=False, blank=True, validators=[MinValueValidator( Decimal('0.01'), "Заказ должен стоить хотя бы 1 цент!" )], ) orderer_wallet = models.ForeignKey( Wallet, to_field='id', on_delete=models.SET_NULL, null=True, related_name='author_wallet_orders' ) executor_wallet = models.ForeignKey( Wallet, to_field='id', on_delete=models.SET_NULL, null=True, related_name='executor_wallet_orders' ) def get_state(self): has_executor = self.executor is not None has_exec_wallet = self.executor_wallet is not None has_orderer_wallet = self.orderer_wallet is not None if not has_executor: return OrderState.FREE elif not has_exec_wallet: return OrderState.TAKEN elif not has_orderer_wallet: return OrderState.READY else: return OrderState.OK def __str__(self): return self.title
class SectionTime(Model): TIME_PATTERNS = ['MWF', 'MW', 'MF', 'WF', 'TH', 'MTWH', 'MTWF'] TIME_PATTERN_CHOICES = [(TIME_PATTERNS.index(time_pattern), time_pattern) for time_pattern in TIME_PATTERNS] time_pattern = IntegerField(choices=TIME_PATTERN_CHOICES) start_time = TimeField() length = DecimalField(max_digits=3, decimal_places=2, verbose_name='Length (Hours)') def __unicode__(self): length_digits = self.length.as_tuple().digits length_hours = length_digits[0] try: length_minutes = (60 * ((length_digits[1] * 10) + length_digits[2]) ) / 100 # Integer math gets nice minute numbers except IndexError: length_minutes = 0 # A bit of a hack to get time and delta to play together nicely. end_time = ( datetime.datetime.combine(datetime.date.today(), self.start_time) + datetime.timedelta(hours=length_hours, minutes=length_minutes)).time() return self.TIME_PATTERNS[self.time_pattern] + " " + unicode( self.start_time) + " - " + unicode(end_time)
class Course(Model): PROXIMITIES = ['DIRECTLY_AFTER', 'SAME_DAY', 'DIFFERENT_DAY'] PROXIMITY_CHOICES = [(PROXIMITIES.index(proximity), proximity) for proximity in PROXIMITIES] prefix = CharField(max_length=4) number = PositiveSmallIntegerField() title = CharField(max_length=60) units = PositiveSmallIntegerField(default=4) wtu = PositiveSmallIntegerField(default=5) requires_equipment = BooleanField(default=False) # Lab Fields has_lab = BooleanField(default=False) lab_requires_equipment = BooleanField(default=False) lab_length = DecimalField(max_digits=3, decimal_places=2, default=0, verbose_name='Lab Length (Hours)') lab_time_proximity = PositiveSmallIntegerField(default=0, choices=PROXIMITY_CHOICES) def __unicode__(self): return self.prefix + " " + unicode(self.number) class Meta: unique_together = ("prefix", "number")
class Record(CommonInfo): created_by = models.ForeignKey(User, on_delete=models.CASCADE) my_catalog = models.ForeignKey(Catalog, on_delete=models.CASCADE, verbose_name='Catalog') # Many records to one Catalog. Deletes all records associated with deleted catalog. acquisition_date = models.CharField(max_length=100, help_text='Please use the following format: <em> YYYY - YYYY </em>', blank=True, default='Unknown') creation_date = models.CharField(max_length=100, help_text='Please use the following format: <em> YYYY </em>', blank=True, default='Unknown') manufacturer = models.ForeignKey('Manufacturer', null=True, blank=True, on_delete=SET_NULL) record_picture = models.ImageField(null=True, blank=True, upload_to="images/") condition_rating = DecimalField( verbose_name='Condition Rating (0 to 5)', default=0, decimal_places=2, max_digits=3, validators=[MinValueValidator(Decimal('0')), MaxValueValidator(Decimal('5'))] ) condition_description = models.TextField(blank=True, help_text='Enter condition description') def get_absolute_url(self): return reverse('record-detail', args=[str(self.id)]) def __str__(self): return f'{self.name} ({self.my_catalog})'
class CoursePrice(Model): """ Information about a course run's price and other ecommerce info """ course_run = ForeignKey(CourseRun) price = DecimalField(decimal_places=2, max_digits=20) is_valid = BooleanField(default=False) created_at = DateTimeField(auto_now_add=True) modified_at = DateTimeField(auto_now=True) @transaction.atomic def save(self, *args, **kwargs): """ Override save to make sure is_valid is only set per one CourseRun """ if self.is_valid and CoursePrice.objects.filter( course_run=self.course_run, is_valid=True ).exclude(id=self.id).exists(): raise EcommerceModelException("Cannot have two CoursePrice objects for same CourseRun marked is_valid") super(CoursePrice, self).save(*args, **kwargs) def __str__(self): """Description for CoursePrice""" return "CoursePrice for {}, price={}, is_valid={}".format(self.course_run, self.price, self.is_valid)
class Module(models.Model): """ A chapter in a CCX course """ uuid = TextField() course = ForeignKey(Course, related_name="modules") title = TextField() price_without_tax = DecimalField(decimal_places=2, max_digits=20, blank=True, null=True) created_at = DateTimeField(auto_now_add=True, blank=True) modified_at = DateTimeField(auto_now=True, blank=True) locator_id = models.CharField(max_length=255, null=True) order = models.IntegerField(default=0) @property def is_available_for_purchase(self): """ Is the module available for purchase? """ return self.course.live and self.price_without_tax is not None # pylint: disable=no-member def __str__(self): """String representation to show in Django Admin console""" return "{title} ({uuid})".format(title=self.title, uuid=self.uuid) class Meta: # pylint: disable=missing-docstring, no-init, old-style-class, too-few-public-methods ordering = ('course_id', 'order') permissions = (EDIT_OWN_PRICE, )
def get_field(self): from django.db.models.fields import IntegerField, DecimalField, BooleanField, TextField from django.core.validators import MaxValueValidator, MinValueValidator args = self.get_args() if self.kind == 0: dbfield = TextField(self.name) if self.kind == 1: dbfield = IntegerField(self.name, validators=[ MinValueValidator(float(args['min'])), MaxValueValidator(float(args['max'])) ]) if self.kind == 2: dbfield = DecimalField(self.name, decimal_places=int(args['prec']), validators=[ MinValueValidator(float(args['min'])), MaxValueValidator(float(args['max'])) ]) if self.kind == 3: dbfield = BooleanField(self.name) if self.kind == 4: choices = [] for item in args['list']: choices.append((len(choices), item)) dbfield = IntegerField(self.name, choices=tuple(choices)) return dbfield
def test_convert_values_to_handle_null_value(self): database_operations = DatabaseOperations(connection) self.assertEqual( None, database_operations.convert_values(None, AutoField(primary_key=True)) ) self.assertEqual( None, database_operations.convert_values(None, DateField()) ) self.assertEqual( None, database_operations.convert_values(None, DateTimeField()) ) self.assertEqual( None, database_operations.convert_values(None, DecimalField()) ) self.assertEqual( None, database_operations.convert_values(None, IntegerField()) ) self.assertEqual( None, database_operations.convert_values(None, TimeField()) )
class DeliveryItem(Model): name = CharField(_('Item Name'), max_length=120, blank=False, null=False) description = CharField(_('Item Description'), max_length=1024, blank=True, null=True) price = DecimalField(_('Item Price'), max_digits=16, decimal_places=2, blank=False, null=False) deliverer_code = CharField(_('Item Code'), max_length=100, blank=True, null=True) deliverer = ForeignKey('Deliverer', on_delete=CASCADE, blank=False, null=False) class Meta: verbose_name = _('Delivery Item') verbose_name_plural = _('Delivery Items') def __repr__(self): return self.name def __str__(self): return self.name
def _resolve_output_field(self): source_fields = self.get_source_fields() if any(isinstance(s, DecimalField) for s in source_fields): return DecimalField() if any(isinstance(s, IntegerField) for s in source_fields): return FloatField() return super()._resolve_output_field() if source_fields else FloatField()
def getRentalsForSummary(current_date=None): result_dict = {} created_today_filter = Q(created_date__date=current_date) ends_today_filter = Q(end_date__date=current_date) paid_filter = Q(paid=True) unpaid_filter = Q(Q(paid=False) | Q(paid__isnull=True)) rentals = Rental.objects.filter( ends_today_filter).annotate( rent_duration=ExpressionWrapper( ( (F('end_date') - F('start_date')) * 0.000001 \ / Value('3600', IntegerField() )), output_field=DecimalField(decimal_places=1) ) ) rent_subquery = rentals.filter(rentaldetail=OuterRef('id')) rentals_detail = RentalDetail.objects.filter( rental__in=rentals).select_related('rental').annotate( rent_duration=Subquery(rent_subquery.values('rent_duration')) ).annotate(item_rent_gross_amt=ExpressionWrapper( F('rent_duration') * F('price') * F('quantity'), output_field=FloatField())) rent_detail_subquery = rentals_detail.filter( rental_id=OuterRef('id')).values('item_rent_gross_amt') test = rent_detail_subquery.values('rental_id').annotate( total=Sum('item_rent_gross_amt')).values('total') rentals = rentals.prefetch_related( Prefetch('rentaldetail_set', rentals_detail)).annotate(total_rent_amt=Subquery(test)) students_with_rentals = Student.objects.filter( Q(rental__in=rentals)).prefetch_related( Prefetch( 'rental_set', rentals)).annotate(student_total_rent_amt=Subquery( rentals.values('student_id').annotate( total_amt=Sum('total_rent_amt')).values( 'total_amt'))).order_by('name').distinct() # Aggregates used for overall summary rentals_counts = rentals.aggregate( ends_today=Count('*'), paid=Count('paid', filter=paid_filter), ) total_rentals_value = rentals_detail.aggregate( sum=Sum('item_rent_gross_amt')) result_dict['count'] = rentals_counts result_dict['total_profit'] = total_rentals_value result_dict['students'] = students_with_rentals return result_dict
class Airport(models.Model): # Airport identification code = CharField(max_length=100, blank=True, default='', null=True) name = CharField(max_length=100, blank=True, default='', null=True) # Airport location country = CharField(max_length=100, blank=True, default='', null=True) state = CharField(max_length=100, blank=True, default='', null=True) city = CharField(max_length=100, blank=True, default='', null=True) latitude = DecimalField(max_digits=20, decimal_places=10, default=0.0) longitude = DecimalField(max_digits=20, decimal_places=10, default=0.0) type = CharField(max_length=100, blank=True, default='', null=True) def __unicode__(self): return "Airport " + self.prefix + " - " + self.name
class TeslaReturn(Model): label = CharField(max_length=50) return_date = DateField() return_amount = DecimalField(max_digits=20, decimal_places=10) created_date = DateTimeField(auto_now_add=True) class Meta(object): db_table = 'tesla_return'
class TrackerPosition(Model): tracker = ForeignKey('Tracker', on_delete=models.CASCADE, verbose_name=_('tracker')) datetime = DateTimeField(auto_now_add=True, verbose_name=_('datetime'), db_index=True) latitude = DecimalField(max_digits=9, decimal_places=6, verbose_name=_('latitude')) longitude = DecimalField(max_digits=9, decimal_places=6, verbose_name=_('longitude')) gps_datetime = DateTimeField(auto_now_add=True, verbose_name=_('datetime'), db_index=True) speed = PositiveIntegerField(null=True, blank=True, verbose_name=_('speed')) direction_longitude = CharField(max_length=20, null=True, blank=True, choices=LONGITUDE_DIRECTION, verbose_name=_('longitude direction')) direction_latitude = CharField(max_length=20, null=True, blank=True, choices=LATITUDE__DIRECTION, verbose_name=_('latitude direction')) direction_angle = PositiveIntegerField(null=True, blank=True, verbose_name=_('direction angle')) message = TextField(verbose_name=_('message')) def __str__(self): return u'{tracker} - {datetime}'.format(tracker=self.tracker, datetime=self.datetime) class Meta: app_label = 'tracker' ordering = [ 'datetime', ] verbose_name_plural = _('tracker positions') verbose_name = _('tracker position')
def test_convert_values_to_handle_null_value(self): from django.db.backends.sqlite3.base import DatabaseOperations convert_values = DatabaseOperations(connection).convert_values self.assertIsNone(convert_values(None, AutoField(primary_key=True))) self.assertIsNone(convert_values(None, DateField())) self.assertIsNone(convert_values(None, DateTimeField())) self.assertIsNone(convert_values(None, DecimalField())) self.assertIsNone(convert_values(None, IntegerField())) self.assertIsNone(convert_values(None, TimeField()))
class Flavor(Model): name = CharField(max_length=255) label = CharField(max_length=255) parent = ForeignKey("self", blank=True, null=True, on_delete=SET_NULL) float_value = FloatField(null=True) decimal_value = DecimalField(null=True, max_digits=10, decimal_places=2) def __str__(self): return self.name
def shop_invoices(self, shop_slug): return self.annotate( coupon_price=Coalesce( Sum('coupon_usages__price_applied', output_field=DecimalField()), Value(0)), price=F('invoice_price_with_discount') + F('logistic_price') - F('coupon_price'), weight=F('total_weight_gram'), ).filter(items__product__FK_Shop__Slug=shop_slug).order_by('-created_datetime')
def post(self, request, format=None): days = request.data.get('days', 10) all_days = request.data.get('download_all', False) today = timezone.now() queryset = ProductExpiry.objects.filter(datetime__gte=today) if not all_days: end_dt = today + timedelta(days=days) queryset = queryset.filter(datetime__lte=end_dt) queryset = queryset.order_by('datetime') \ .select_related('product') \ .annotate(diff_days=ExpressionWrapper(F('datetime') - today, output_field=DurationField()), total_value=ExpressionWrapper(F('product__stock') * F('product__price'), output_field=DecimalField())) if not os.path.exists('temp_files'): os.makedirs('temp_files') file_name = f'temp_files/{uuid4()}.xlsx' workbook = xlsxwriter.Workbook(file_name) worksheet = workbook.add_worksheet() headers = ['Sl.no', 'Product', 'MRP', 'Quantity', 'Total MRP Value', 'Expiry Day', 'No of Days for Expiry'] row = 0 col = 0 for header in headers: worksheet.write(row, col, header) col = col + 1 values = queryset.values('product__name', 'product__price', 'product__stock', 'datetime', 'diff_days', 'total_value') row = 1 col = 0 for entry in values: worksheet.write(row, col, row) worksheet.write(row, col + 1, entry['product__name']) worksheet.write(row, col + 2, entry['product__price']) worksheet.write(row, col + 3, entry['product__stock']) worksheet.write(row, col + 4, entry['total_value']) worksheet.write(row, col + 5, entry['datetime'].strftime('%d/%m/%y')) worksheet.write(row, col + 6, entry['diff_days'].days) row += 1 workbook.close() with open(file_name, 'rb') as fi: fl = File(fi, name=os.path.basename(fi.name)) report = ExpiryReport.objects.create(user=self.request.user, file=fl, no_of_days=days) try: os.remove(file_name) except OSError: pass return Response(data=ExpiryReportSerializer(report, context={'request': self.request}).data, status=status.HTTP_201_CREATED)
def test_compare_money_field_with_django_field(): field_1 = models.MoneyField( amount_field="money_net_amount", currency_field="currency" ) field_2 = DecimalField(default="5", max_digits=9, decimal_places=2) # Comparision is based on creation_counter attribute assert field_1 < field_2 assert not field_1 > field_2 field_2.creation_counter -= 1 assert field_1 == field_2
class Line(Model): """ A line in an order """ course_key = TextField() order = ForeignKey(Order) price = DecimalField(decimal_places=2, max_digits=20) description = TextField(blank=True, null=True) created_at = DateTimeField(auto_now_add=True) modified_at = DateTimeField(auto_now=True)