def get_feedback(self): """ Return all feedback for the participant. Activity chairs see the complete history of feedback (without the normal "clean slate" period). The only exception is that activity chairs cannot see their own feedback. """ return ( models.Feedback.everything.filter(participant=self.object.participant) .exclude(participant=self.chair) .select_related('leader', 'trip') .prefetch_related('leader__leaderrating_set') .annotate( display_date=Least('trip__trip_date', Cast('time_created', DateField())) ) .order_by('-display_date') )
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(blank=True, null=True) decimal_value = DecimalField(blank=True, null=True, max_digits=10, decimal_places=2) uuid = UUIDField(default=uuid.uuid4) datetime = DateTimeField(blank=True, null=True) date = DateField(blank=True, null=True) time = TimeField(blank=True, null=True) duration = DurationField(blank=True, null=True) def __str__(self): return self.name
def get_context_data(self, **kwargs): context = super(UserAboutPage, self).get_context_data(**kwargs) ratings = context['ratings'] = self.object.ratings.order_by('-contest__end_time').select_related('contest') \ .defer('contest__description') context['rating_data'] = mark_safe(json.dumps([{ 'label': rating.contest.name, 'rating': rating.rating, 'ranking': rating.rank, 'link': reverse('contest_ranking', args=(rating.contest.key,)), 'timestamp': (rating.contest.end_time - EPOCH).total_seconds() * 1000, 'date': date_format(rating.contest.end_time, _('M j, Y, G:i')), 'class': rating_class(rating.rating), 'height': '%.3fem' % rating_progress(rating.rating), } for rating in ratings])) if ratings: user_data = self.object.ratings.aggregate(Min('rating'), Max('rating')) global_data = Rating.objects.aggregate(Min('rating'), Max('rating')) min_ever, max_ever = global_data['rating__min'], global_data['rating__max'] min_user, max_user = user_data['rating__min'], user_data['rating__max'] delta = max_user - min_user ratio = (max_ever - max_user) / (max_ever - min_ever) if max_ever != min_ever else 1.0 context['max_graph'] = max_user + ratio * delta context['min_graph'] = min_user + ratio * delta - delta submissions = ( self.object.submission_set .annotate(date_only=Cast('date', DateField())) .values('date_only').annotate(cnt=Count('id')) ) context['submission_data'] = mark_safe(json.dumps({ date_counts['date_only'].isoformat(): date_counts['cnt'] for date_counts in submissions })) context['submission_metadata'] = mark_safe(json.dumps({ 'min_year': ( self.object.submission_set .annotate(year_only=ExtractYear('date')) .aggregate(min_year=Min('year_only'))['min_year'] ), })) return context
class Event(models.Model): def __str__(self): return '%s' % (self.name) name = TextField() # place = PointField(blank=True, null=True) description = TextField(blank=True, null=True) date = DateField(blank=True, null=True) # contact = ForeignKey('contactlist.Contact') @classmethod def serialize(cls): return json.dumps([{ 'id': p.id, 'name': p.name, 'description': p.description, 'date': p.date.isoformat() } for p in cls.objects.all()])
class Profile(QuicksellModel): """User profile info.""" user = OneToOneField( User, related_name='_profile', primary_key=True, editable=False, on_delete=CASCADE ) uuid = UUIDField(default=uuid.uuid4, unique=True, editable=False) date_created = DateField(default=date.today, editable=False) full_name = CharField(max_length=100, blank=True) about = TextField(blank=True) online = BooleanField(default=True) rating = IntegerField(default=0) avatar = ImageField(null=True, blank=True, upload_to='images/avatars') location = ForeignKey(**location_fk_kwargs) def __str__(self): return str(self.user) + "'s profile."
class ResultadoCanal(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) base = models.IntegerField("Número total de base", blank=True) engajamento = models.DecimalField("Engajamento do canal", max_digits=4, decimal_places=2, blank=True, null=True) quando = DateField("Informação do dia", blank=True, null=True) canal = models.ForeignKey(CanalProprietario, null=True, on_delete=models.SET_NULL, verbose_name="Canal") def __str__(self): return "%s" % (self.canal)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['future_events'] = Event.objects.published().future().all() context['future_events_count'] = Event.objects.published().future( ).count() context['future_events_by_date'] = Event.objects.published().future()\ .annotate(day=Cast('event_date', DateField())).values('day') \ .annotate(count=Count('day')).values('day', 'count')\ .order_by('day') context['future_events_by_weekday'] = Event.objects.published().future()\ .annotate(weekday=ExtractWeekDay('event_date')).values('weekday')\ .annotate(count=Count('id')).values('weekday', 'count')\ .order_by('weekday') context['organizers_count'] = Organizer.objects.count() context['speakers_count'] = Speaker.objects.count() context['active_users_count'] = User.objects.filter( is_active=True).count() return context
class CardSet(Model): class Meta: ordering = ["set_no"] set_no = IntegerField(blank=True, null=True) country = CountryField() name = CharField(max_length=255, blank=True) release = DateField(blank=True, null=True) logo = ImageField(upload_to='set', null=True, blank=True) partial_url = CharField(max_length=255, blank=True) official_count = IntegerField(blank=True, null=True) def __unicode__(self): """ The string representation of the card set. """ return self.name
def test_convert_values_to_handle_null_value(self): from django.db.backends.sqlite3.base import DatabaseOperations 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()))
def posts(req): POSTS_PER_FETCH = 30 newer_than = try_str_to_int( req.GET.get('newer_than', None) ) older_than = try_str_to_int( req.GET.get('older_than', None) ) only_user_posts = req.GET.get('pid', None) if newer_than: query = Q(pk__gt=newer_than) prefix = '' elif older_than: query = Q(pk__lt=older_than) prefix = '-' else: query = Q() prefix = '-' if only_user_posts: pid = try_str_to_int(only_user_posts) profile = get_object_or_404(DP, pk=pid) posts = ( Post.objects .filter(profile=profile, is_deleted=False) .select_related('profile') .prefetch_related('photos') ) else: posts = req.user.profile.matching_posts ordering = [ prefix + 'created_date', '-is_user_vip', prefix + 'created' ] posts = ( posts .filter(query) .annotate(created_date=Cast('created', DateField())) .annotate( is_user_vip=DP.is_vip_annotation('profile__status')) .order_by(*ordering) [:POSTS_PER_FETCH] ) return JsonResponse({'posts': serialize_posts(posts)})
class Diagnose(models.Model): test_date = DateField(auto_now=True) patient_name = models.CharField(max_length=220, verbose_name="Full Name") patient_country = models.CharField(max_length=220, verbose_name="Country") patient_city = models.CharField(max_length=220, verbose_name="City") patient_phone = models.CharField(max_length=20, default="", verbose_name="Phone Number") patient_email = models.EmailField(max_length=50, blank=True, default="", verbose_name="Email Address") x_ray_image = CloudinaryField(null=False, blank=False, verbose_name="X-Ray Image") # after analysing image the api hosts the image to imgur and sends back url of the image analysed_image = models.CharField(max_length=2083, default="") affected_percentage = models.IntegerField(default=-1)
def xml_to_field(field_type, **kwargs): if field_type == 'int': #TODO fix max_length field = IntegerField(max_length=MAX_LENGHT_INT, **kwargs) if field_type == 'char': #TODO fix max_length field = CharField(max_length=MAX_LENGHT_CHAR, **kwargs) if field_type == 'text': field = TextField(**kwargs) if field_type == 'boolean': field = BooleanField(**kwargs) if field_type == 'date': field = DateField(**kwargs) if field_type == 'datetime': field = DateTimeField(**kwargs) if field_type == 'float': field = FloatField(**kwargs) return field
class Printer(NetworkDevice): department = ForeignKey(Department, verbose_name='Department', on_delete=CASCADE) sub_department = ForeignKey(SubDepartment, verbose_name='Sub Department', on_delete=CASCADE) model = CharField(max_length=25, verbose_name='Model') serial_number = CharField(max_length=20, verbose_name='Serial Number', blank=True, null=True, unique=True, default=None) property_id = CharField(max_length=50, verbose_name='Cal Poly Property ID', blank=True, null=True, unique=True, default=None) location = CharField(max_length=100, verbose_name='Location', blank=True, null=True) date_purchased = DateField(verbose_name='Date Purchased') description = CharField(max_length=100, verbose_name='Description') dhcp = BooleanField(default=False) def __str__(self): return self.printer_name def save(self, *args, **kwargs): """Uppercase field names on save.""" for field_name in ['printer_name', 'mac_address', 'serial_number', 'property_id']: value = getattr(self, field_name, None) if value: setattr(self, field_name, value.upper()) for field_name in ['serial_number', 'property_id']: value = getattr(self, field_name, None) if not value: setattr(self, field_name, None) if not self.ip_address: self.ip_address = None self.dhcp = True if self.dhcp: self.ip_address = None super(Printer, self).save(*args, **kwargs)
def list(self, request): app = self.request.query_params.get('app', False) aggregation = self.request.query_params.get('aggregation', False) name = self.request.query_params.get('name', False) value = self.request.query_params.get('value', False) queryFilter = dict(self.request.query_params) already_use = ['app', 'aggregation', 'name', 'value'] for item in already_use: queryFilter.pop(item, None) print(queryFilter) if aggregation: if globals()[app]._meta.get_field(name).get_internal_type() == 'DateTimeField': name = Cast(F(name), output_field=DateField()) elif globals()[app]._meta.get_field(name).get_internal_type() == 'ForeignKey': try: globals()[app]._meta.get_field(name).related_model._meta.get_field('name') name = F(name + "__name") except FieldDoesNotExist: name = F(name + "__label") else: name = F(name) if 'start_date' in queryFilter and 'end_date' in queryFilter: if app == 'Order': filterQuery = {"createDateTime__range": [queryFilter['start_date'][0], queryFilter['end_date'][0]]} elif app == 'OrderDetail': filterQuery = {"order__createDateTime__range": [queryFilter['start_date'][0], queryFilter['end_date'][0]]} elif app == 'Stock': filterQuery = {"stockDate__range": [queryFilter['start_date'][0], queryFilter['end_date'][0]]} result = globals()[app].objects.filter(**filterQuery) else: result = globals()[app].objects result = result.values(**{'name': name}).order_by('name').annotate( **{'value': getattr(models, aggregation)(value)}) totalcount = result.count() # result = self.pagination_class.paginate_queryset(queryset=result, request=request, view=self) serializer = self.get_serializer_class()(result, many=True) data = serializer.data return Response({"totalCount": totalcount, "aggregation": aggregation, "result": data})
def results_iter(self): """ Returns an iterator over the results from executing this query. """ resolve_columns = hasattr(self, 'resolve_columns') if resolve_columns: from django.db.models.fields import DateField fields = [DateField()] else: from django.db.backends.util import typecast_date needs_string_cast = self.connection.features.needs_datetime_string_cast offset = len(self.query.extra_select) for rows in self.execute_sql(MULTI): for row in rows: date = row[offset] if resolve_columns: date = self.resolve_columns(row, fields)[offset] elif needs_string_cast: date = typecast_date(str(date)) if isinstance(date, datetime.datetime): date = date.date() yield date
class Forløb(models.Model): """Forløb er et Emne, der gennemgås i en Klasse fra et bestemt tidspunkt (`påbegyndt`) og som har en planlagt `varighed`.""" id = AutoField(primary_key=True, verbose_name='Forløbs-løbenummer (automatisk)') emne = ForeignKey('Emne', on_delete=models.RESTRICT, null=True) klasse = ForeignKey('Klasse', on_delete=models.RESTRICT, null=True) oprettet = models.DateTimeField( #default=timezone.now() auto_now_add= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now_add ) opdateret = models.DateTimeField( # NB: Dato odateres ved Model.save() ikke ved QuerySet.update(), se dokumenation! #default=timezone.now(), auto_now= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now ) titel = CharField(max_length=20, help_text='Overskrift for forløbet') påbegyndt = DateField(help_text='Dato for planlagt start af forløbet') varighed = IntegerField(help_text='Forventet antal lektioner/moduler') kommentar = TextField( max_length=500, null=True, blank=True, help_text= 'Præsentation til holdets elever af det konkrete forløb i klassen') class Meta: ordering = ['klasse', 'emne'] verbose_name_plural = 'forløb' def __str__(self): return f"{self.klasse.kortnavn}: fra {self.påbegyndt} -- {self.emne}" def get_absolute_url(self): """Returnerer URL, der tilgår et bestemt Forløb.""" return reverse('forloeb-detalje-visning', args=[str(self.id)])
def test_DateField(self): self.assertIsInstance( DateField().get_prep_value(datetime.date.today()), datetime.date)
class Fiscal(Transform): lookup_name = None extract_field = None offset = '3 months' def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) sql = "date_part('%s', %s + interval '%s')" % (self.extract_field, sql, self.offset) return sql, params @property def output_field(self): return IntegerField() class FiscalYear(Fiscal): lookup_name = 'fyear' extract_field = 'year' class FiscalQuarter(Fiscal): lookup_name = 'fquarter' extract_field = 'quarter' Field.register_lookup(NotEqual) DateField.register_lookup(FiscalYear) DateField.register_lookup(FiscalQuarter)
from copy import copy from django.conf import settings from django.db.models.expressions import Func, Value from django.db.models.fields import ( DateField, DateTimeField, Field, IntegerField, TimeField, ) from django.db.models.query_utils import RegisterLookupMixin from django.utils import timezone from django.utils.functional import cached_property from django.utils.six.moves import range class Lookup(object): lookup_name = None def __init__(self, lhs, rhs): self.lhs, self.rhs = lhs, rhs self.rhs = self.get_prep_lookup() if hasattr(self.lhs, 'get_bilateral_transforms'): bilateral_transforms = self.lhs.get_bilateral_transforms() else: bilateral_transforms = [] if bilateral_transforms: # We should warn the user as soon as possible if he is trying to apply # a bilateral transformation on a nested QuerySet: that won't work. # We need to import QuerySet here so as to avoid circular from django.db.models.query import QuerySet if isinstance(rhs, QuerySet): raise NotImplementedError("Bilateral transformations on nested querysets are not supported.") self.bilateral_transforms = bilateral_transforms def apply_bilateral_transforms(self, value): for transform in self.bilateral_transforms:
class ResidenciaAut(models.Model): tipo_choice = ( ('C', 'Colegio'), ('M', 'Mixta'), ) expediente = models.CharField('N° de Expediente del Ministerio de Salud', max_length=12, null=True, blank=True, default='0-0-00', help_text='####-####/##') a_Comienzo = PositiveSmallIntegerField('Año') especialidad = models.ForeignKey(Especialidad, related_name='+', null=True, blank=True) institucion = models.ForeignKey('Institucion', related_name='+', null=True, blank=True) cantA_1 = PositiveSmallIntegerField('1er. Año') cantA_2 = PositiveSmallIntegerField('2do. Año') cantA_3 = PositiveSmallIntegerField('3er. Año') cantA_4 = PositiveSmallIntegerField('4to. Año') jefeResidentes = PositiveSmallIntegerField('Jefe de Residentes') fechaEvaluacColMed = DateField('Fecha de Evaluación', blank=True, null=False) fechaEvaluacMixta = DateField('Fecha de Evaluación Mixta', blank=True, null=True) fechaCeseActividad = DateField('Fecha de Vencimiento Acreditación', blank=True, null=True) jefeServicio = models.CharField('Jefe de Servicio', max_length=50, blank=True, null=True) coordinador = models.CharField('Coordinador', max_length=50, blank=True, null=True) asesorDocente = models.CharField('Asesor Docente', max_length=150, blank=True) jefedocencia = models.CharField('Jefe Docencia', max_length=150, blank=True) tipo = models.CharField(max_length=2, choices=tipo_choice, blank=True) memo = models.TextField('memo', null=True, blank=True) instructorr = models.CharField('Instructor de Residentes', max_length=150, blank=True) class Meta: verbose_name = "Residencia" verbose_name_plural = "Residencias" def __unicode__(self): return unicode(self.a_Comienzo) def fechaEvalNoNula(self): if not self.fechaEvaluacColMed: return '' else: return self.fechaEvaluacColMed.strftime("%d/%m/%Y") def fechaCeseActividadNoNula(self): if not self.fechaCeseActividad: return '' else: return self.fechaCeseActividad.strftime("%d/%m/%Y") def memoNoNulo(self): if not self.memo: return '.' else: return self.memo def nombreTipo(self): if self.tipo == 'C': return 'Colegio' else: return 'Mixto' def sumaCantA(self): return self.cantA_1 + self.cantA_2 + self.cantA_3 + self.cantA_4
def output_field(self): return DateField()
lookup_name = 'week_day' class HourTransform(DateTransform): lookup_name = 'hour' class MinuteTransform(DateTransform): lookup_name = 'minute' class SecondTransform(DateTransform): lookup_name = 'second' DateField.register_lookup(YearTransform) DateField.register_lookup(MonthTransform) DateField.register_lookup(DayTransform) DateField.register_lookup(WeekDayTransform) TimeField.register_lookup(HourTransform) TimeField.register_lookup(MinuteTransform) TimeField.register_lookup(SecondTransform) DateTimeField.register_lookup(DateTimeDateTransform) DateTimeField.register_lookup(YearTransform) DateTimeField.register_lookup(MonthTransform) DateTimeField.register_lookup(DayTransform) DateTimeField.register_lookup(WeekDayTransform) DateTimeField.register_lookup(HourTransform) DateTimeField.register_lookup(MinuteTransform)
def with_effective_valid_between(self): """ There are five ways in which measures can get end dated: 1. Where the measure is given an explicit end date on the measure record itself 2. Where the measure's generating regulation is a base regulation, and the base regulation itself is end-dated 3. Where the measure's generating regulation is a modification regulation, and the modification regulation itself is end-dated 4. Where the measure's generating regulation is a base regulation, and any of the modification regulations that modify it are end-dated 5. Where the measure's generating regulation is a modification regulation, and the base regulation that it modifies is end-dated Numbers 2–5 also have to take account of the "effective end date" which if set should be used over any explicit date. The effective end date is set when other types of regulations are used (abrogation, prorogation, etc). """ # Computing the end date for case 4 is expensive because it involves # aggregating over all of the modifications to the base regulation, # where there is one. So we pull this out into a CTE to let Postgres # know that none of this caluclation depends on the queryset filters. # # We also turn NULLs into "infinity" such that they sort to the top: # i.e. if any modification regulation is open-ended, so is the measure. # We then turn infinity back into NULL to be used in the date range. Regulation = self.model._meta.get_field( "generating_regulation", ).remote_field.model end_date_from_modifications = With( Regulation.objects.annotate(amended_end_date=NullIf( Max( Coalesce( F("amendments__enacting_regulation__effective_end_date" ), EndDate( "amendments__enacting_regulation__valid_between"), Cast(Value("infinity"), DateField()), ), ), Cast(Value("infinity"), DateField()), ), ), "end_date_from_modifications", ) return (end_date_from_modifications.join( self, generating_regulation_id=end_date_from_modifications.col.id, ).with_cte(end_date_from_modifications).annotate( db_effective_end_date=Coalesce( # Case 1 – explicit end date, which is always used if present EndDate("valid_between"), # Case 2 and 3 – end date of regulation F("generating_regulation__effective_end_date"), EndDate("generating_regulation__valid_between"), # Case 4 – generating regulation is a base regulation, and # the modification regulation is end-dated end_date_from_modifications.col.amended_end_date, # Case 5 – generating regulation is a modification regulation, # and the base it modifies is end-dated. Note that the above # means that this only applies if the modification has no end date. F("generating_regulation__amends__effective_end_date"), EndDate("generating_regulation__amends__valid_between"), ), db_effective_valid_between=Func( StartDate("valid_between"), F("db_effective_end_date"), Value("[]"), function="DATERANGE", output_field=TaricDateRangeField(), ), ))
class Video(models.Model): """ Præsentation på video (eller i personligt fremmøde) af opgave stillet i forbindelse med et Forløb. https://trello.com/c/ZReTY2UN """ id = AutoField( primary_key=True, verbose_name='Løbenummer (automatisk) for videopræsentation') forløb = ForeignKey('Forløb', on_delete=models.RESTRICT, null=False) elev = ForeignKey('Elev', on_delete=models.RESTRICT, null=False) oprettet = models.DateTimeField( #default=timezone.now() auto_now_add= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now_add ) opdateret = models.DateTimeField( # NB: Dato odateres ved Model.save() ikke ved QuerySet.update(), se dokumenation! #default=timezone.now(), auto_now= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now ) """ Valideres til at ligge efter `forløb.påbegyndt` og før 3 måneder efter denne dato. Redundant, når `oprettet` haves? """ stillet = DateField( help_text='Dato, hvor opgaven blev stillet til elev (eller hold)') """Afleveringsfrist Valideres til at ligge efter `stillet` og højst 3 måneder efter denne dato.""" frist = DateTimeField( help_text='Dato og tid for seneste aftalte aflevering') """ Gerne oprettelses-tidsstempel fra video-netside Valideres til at ligge efter `frist` og højst 3 måneder efter `frist`. """ indleveret = DateField(help_text='Dato og tid for faktisk aflevering') opgave = CharField(max_length=100, help_text='Opgavetekst for SOLO aktivitet') #""" # Knytter eventuelt opgaven, og dermed præsentationen, # til en HookED On Thinking aktivitet. # I bekræftende fald giver relationen et paradigmatisk - ikke opgave-konkret - # SOLO-retteark til SOLO-niveau. #""" # solo_aktivitet ManyToManyField url = URLField(help_text='Videoens placering (fx skjult på YouTube)') egen_solo = CharField(max_length=3, choices=[('pre', 'Præstrukturelt niveau'), ('uni', 'Unistrukturelt niveau'), ('mul', 'Multistrukturelt niveau'), ('rel', 'Relationelt niveau'), ('udv', 'Udvidet-abstrakt niveau')], null=True, verbose_name="Elevens egen bedømmelse efter SOLO") """Hvis feltet udfyldes, sker det EFTER elevens egen SOLO bedømmelse.""" lærer_solo = CharField(max_length=3, choices=[('pre', 'Præstrukturelt niveau'), ('uni', 'Unistrukturelt niveau'), ('mul', 'Multistrukturelt niveau'), ('rel', 'Relationelt niveau'), ('udv', 'Udvidet-abstrakt niveau')], null=True) """ i stedet for (eller som supplement til) SOLO-bedømmelse """ egen_bedømmelse = CharField( max_length=100, null=True, verbose_name="Elevens egen bedømmelse i fri tekst") """ I stedet for (eller som supplement til) SOLO-bedømmelse. Hvis feltet udfyldes, sker det efter elevens egen bedømmelse. """ lærer_bedømmelse = CharField(max_length=100, null=True) class Meta: ordering = ['forløb', 'frist', 'elev'] def __str__(self): return self.__class__.__name__ + f" fra {self.elev} indleveret d. {self.indleveret}." def get_absolute_url(self): """Returnerer URL, der tilgår en bestemt Video.""" return reverse('videopraesentation-detalje-visning', args=[str(self.id)])
lookup_name = "quarter" class ExtractHour(Extract): lookup_name = "hour" class ExtractMinute(Extract): lookup_name = "minute" class ExtractSecond(Extract): lookup_name = "second" DateField.register_lookup(ExtractYear) DateField.register_lookup(ExtractMonth) DateField.register_lookup(ExtractDay) DateField.register_lookup(ExtractWeekDay) DateField.register_lookup(ExtractIsoWeekDay) DateField.register_lookup(ExtractWeek) DateField.register_lookup(ExtractIsoYear) DateField.register_lookup(ExtractQuarter) TimeField.register_lookup(ExtractHour) TimeField.register_lookup(ExtractMinute) TimeField.register_lookup(ExtractSecond) DateTimeField.register_lookup(ExtractHour) DateTimeField.register_lookup(ExtractMinute) DateTimeField.register_lookup(ExtractSecond)
class Book(Model): title = CharField(max_length=255) date_published = DateField()
def index(request, status='all'): all_applications = Application.objects.filter(user=request.user).order_by('-last_updated').annotate(number_of_events=Count('event'), date=Cast('last_updated', DateField())) active_applications = Application.objects.filter(user=request.user, is_active=True).order_by('-last_updated').annotate(number_of_events=Count('event'), date=Cast('last_updated', DateField())) if status == 'all': applications = active_applications elif status == 'Archived': applications = Application.objects.filter(user=request.user, is_active=False).order_by('-last_updated').annotate(number_of_events=Count('event'), date=Cast('last_updated', DateField())) else: applications = Application.objects.filter(user=request.user, status=status, is_active=True).order_by('-last_updated').annotate(number_of_events=Count('event'), date=Cast('last_updated', DateField())) status_count = { 'Job_Offer': 0, 'On_Site_Interview': 0, 'Technical_Interview': 0, 'Phone_Screen': 0, 'Application_Submitted': 0, 'All': len(active_applications), 'Archived': len(all_applications) - len(active_applications), } for app in applications: if app.status: app.progress = get_progress(app.status) app.icon = get_icon(app.status) else: app.progress = 0 app.icon = 'icon-question-sign' if Event.objects.filter(application = app): app.recent_event = Event.objects.filter(application = app).latest('event_date') else: app.recent_event = 'This application has no events' for application in all_applications: if application.status and application.is_active: status = application.status.replace(' ', '_') status_count[status] += 1 data = namedtuple('Data', status_count.keys())(**status_count) context = { 'applications': applications, 'recent_apps': all_applications[:3], 'template_data': data } return render(request, 'applications/application-list.html', context)
lookup_name = 'quarter' class ExtractHour(Extract): lookup_name = 'hour' class ExtractMinute(Extract): lookup_name = 'minute' class ExtractSecond(Extract): lookup_name = 'second' DateField.register_lookup(ExtractYear) DateField.register_lookup(ExtractMonth) DateField.register_lookup(ExtractDay) DateField.register_lookup(ExtractWeekDay) DateField.register_lookup(ExtractWeek) DateField.register_lookup(ExtractIsoYear) DateField.register_lookup(ExtractQuarter) TimeField.register_lookup(ExtractHour) TimeField.register_lookup(ExtractMinute) TimeField.register_lookup(ExtractSecond) DateTimeField.register_lookup(ExtractHour) DateTimeField.register_lookup(ExtractMinute) DateTimeField.register_lookup(ExtractSecond)
def test_DateField(self): lazy_func = lazy(lambda: datetime.date.today(), datetime.date) self.assertIsInstance(DateField().get_prep_value(lazy_func()), datetime.date)
class Visite(Model): state = BooleanField(default=False) id_habitation = ForeignKey(Habitation, on_delete=CASCADE) #id_logement date = DateField() hour = TimeField() id_seeker = ForeignKey(Seeker, on_delete=CASCADE)
class CaThi(models.Model): ''' Thiet lap mot ca thi, trong do co danh sach cau hoi de tu do lam cac de thi cho tung sinh vien ''' title = CharField(verbose_name="Ca thi", max_length=200, blank=False) description=TextField(verbose_name="Ghi chú", blank=True, null=True) mon_thi = ForeignKey(MonThi, blank=False, null=False, verbose_name="Môn thi") # lop_thi = ForeignKey(Lop, blank=False, null=False, # verbose_name="Lớp thi") # ds_thisinh = ForeignKey(Lop_CaThi, blank=False, null=False, # verbose_name="Danh sách thí sinh") ds_giamthi = ManyToManyField(GiaoVien, verbose_name=u'Danh sách giám thị coi thi') ds_thisinh = ManyToManyField(SinhVien, blank=False, verbose_name=u"Danh sách thí sinh") ds_thisinh.help_text = 'Tìm kiếm theo họ tên sinh viên hoặc mã lớp.' ngay_thi = DateField(verbose_name="Ngày thi") tg_bat_dau=TimeField(verbose_name="Thời gian bắt đầu") tg_ket_thuc=TimeField(verbose_name="Thời gian kết thúc") ds_cau_hoi = CommaSeparatedIntegerField(max_length=1024, verbose_name="Danh sach cau hoi (ids)") # setting = ManyToManyField(QuestionGroup_Setting, # verbose_name="Thiết lập cấu hình ca thi") tao_moi_de_thi = BooleanField(blank=False, null=False, verbose_name="Tạo mới đề thi cho các sinh viên", default=True) random_order = BooleanField(blank=False, null=False, verbose_name="Hiển thị câu hỏi ngẫu nhiên", default=True) answers_at_end = BooleanField(blank=False, null=False, verbose_name="Hiển thị câu trả lời khi kết thúc", default=False) result_at_end = BooleanField(blank=False, null=False, verbose_name="Hiển thị kết quả khi kết thúc", default=True) exam_paper = BooleanField(blank=False, null=False, verbose_name="Lưu bài thi", default=True) single_attempt = BooleanField(blank=False, null=False, verbose_name="Mỗi người một đề thi", default=True) pass_mark = PositiveIntegerField(verbose_name="Điểm đạt yêu cầu") success_text = TextField(blank=True, verbose_name="Thông báo được hiển thị nếu thí sinh vượt qua") fail_text = TextField(blank=True, verbose_name="Thông báo được hiển thị nếu thí sinh không vượt qua") draft=BooleanField(verbose_name="Bản nháp", default=False) class Meta: verbose_name = "Ca thi" verbose_name_plural = "Danh sách ca thi" def __unicode__(self): return u'%s' %(self.title) def save(self, *args, **kwargs): # luu CaThi va Cathi_Setting # super(CaThi, self).save(*args, **kwargs) # # lay danh sach cau hoi cho ca thi # # lay cathi_setting questionGroup_settings = QuestionGroup_Setting.objects.filter(ca_thi__exact=self) # # cac cau hoi cua de thi questions = [] for cathi_setting in questionGroup_settings: # lay cau hoi theo nhom va loai (type) qs = Question.objects.filter(mon_thi=self.mon_thi, question_type = cathi_setting.question_type, question_group = cathi_setting.question_group) # lay id q_ids = qs.values_list('id', flat=True) # lay ngau nhien so cau hoi questions += sample(q_ids, cathi_setting.num_of_questions) self.ds_cau_hoi = ','.join(map(str, questions)) + "," # luu CaThi-ds_cauhoi super(CaThi, self).save(*args, **kwargs) # tao de thi cho tung sinh vien # lay danh sach sinh vien cua lop # dsSV = SinhVien.objects.filter(lop=self.lop_thi) dsSV = self.ds_thisinh.all() if(self.tao_moi_de_thi == False): return # voi moi sinh vien, tao mot de thi for sv in dsSV: # tao de thi dethi = DeThi.objects.update_or_create(sinh_vien=sv, ca_thi=self, )[0] # lay ngau nhien cau hoi trong ngan hang de ds_cauhoi = sample(questions, len(questions)) ds_cauhoi_answer = [] for cauhoi_id in ds_cauhoi: # lay cau hoi voi id tuong ung q = Question.objects.get(id=cauhoi_id) # neu cau hoi la multichoice question thi hoan doi thu tu # cau tra loi if q.question_type == MCQUESTION: # lay cac cau tra loi cua cau hoi nay # q = (MCQuestion)q # answers = Answer.objects.filter(question=q.id) q.__class__ = MCQuestion answers = q.getAnswers() # lay id cua cac cau hoi answer_ids = answers.values_list('id', flat=True) # dao thu tu cau tra loi answer_ids = sample(answer_ids, len(answer_ids)) # add vao mot dictionary ds_cauhoi_answer.append((cauhoi_id, answer_ids)) elif q.question_type == TFQUESTION: ds_cauhoi_answer.append((cauhoi_id, [1, 0])) else: ds_cauhoi_answer.append((cauhoi_id, [])) dethi.ds_cau_hoi = json.dumps(ds_cauhoi_answer) dethi.save()
class Date_slots(Model): date = DateField()