class DCFModel(DjangoModel, __implements__, IDCFModel[T]): class Meta: abstract = True objects: BaseManager[T] id = UUIDField(unique=True, primary_key=True, default=uuid4, editable=False) created_at = DateTimeField(auto_now_add=True) def __repr__(self) -> str: return f"<{self.__class__.__name__}: {self.pk}>" def __str__(self) -> str: return f"<{self.__class__.__name__}: {self.pk}>" @classmethod def from_model(cls, model: T) -> DCFModel[T]: assert isinstance(model, DCFModel) return model @classmethod def from_model_type(cls, model: Type[T]) -> Type[DCFModel[T]]: assert issubclass(model, DCFModel) return model
class Mark(models.Model): # old: nb2_mark TYPES = ((1, "answerplease"), (3, "approve"), (5, "reject"), (7, "favorite"), (9, "hide")) type = IntegerField(choices=TYPES) # old: id_type integer NOT NULL ctime = DateTimeField(default=datetime.now) # old: ctime timestamp comment = ForeignKey(Comment) # old: id_ann integer NOT NULL user = ForeignKey(User) # old: id_user integer NOT NULL
class PatientVaccination(models.Model): patient = models.ForeignKey(UserProfile) creationdate = DateTimeField(auto_now_add=True, auto_now=False) patient_vaccine = models.ForeignKey(Vaccine) vaccinedose = models.ForeignKey(VaccineDose) dateofvaccinereceiption = models.DateField() locationofreception = models.CharField(max_length=150, blank=True) def __unicode__(self): return smart_unicode(self.patient) def monthly_patients(self): dataframe = read_frame(PatientVaccination.objects.all()) dataframe['month'] = [ date.strftime('%B') for date in dataframe['dateofvaccinereceiption'] ] groups = dataframe.groupby('month')['id'].count() return groups def monthly_vaccine(self): dataframe = read_frame(PatientVaccination.objects.all()) dataframe['month'] = [ date.strftime('%B') for date in dataframe['dateofvaccinereceiption'] ] groups = dataframe.groupby(['month', 'patient_vaccine' ])['id'].count().reset_index(name='count') return groups
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 Line(Model): """ A line in an order. This contains information about a specific item to be purchased. """ course_key = TextField(db_index=True) order = ForeignKey(Order, on_delete=CASCADE) 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) def __str__(self): """Description for Line""" return "Line for order {}, course_key={}, price={}".format( self.order.id, self.course_key, self.price)
class Receipt(Model): """ The contents of the message from CyberSource about an Order fulfillment or cancellation """ order = ForeignKey(Order, null=True, on_delete=CASCADE) data = JSONField() created_at = DateTimeField(auto_now_add=True) modified_at = DateTimeField(auto_now=True) def __str__(self): """Description of Receipt""" if self.order: return "Receipt for order {}".format(self.order.id) else: return "Receipt with no attached order"
class BaseSchedule(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mon_start_1 = models.TimeField() mon_end_1 = models.TimeField() mon_start_2 = models.TimeField() mon_end_2 = models.TimeField() tue_start_1 = models.TimeField() tue_end_1 = models.TimeField() tue_start_2 = models.TimeField() tue_end_2 = models.TimeField() wed_start_1 = models.TimeField() wed_end_1 = models.TimeField() wed_start_2 = models.TimeField() wed_end_2 = models.TimeField() thur_start_1 = models.TimeField() thur_end_1 = models.TimeField() thur_start_2 = models.TimeField() thur_end_2 = models.TimeField() fri_start_1 = models.TimeField() fri_end_1 = models.TimeField() fri_start_2 = models.TimeField() fri_end_2 = models.TimeField() created = DateTimeField(auto_now_add=True) class Meta: abstract = True
class Worker(TelegramUser): created = DateTimeField(default=timezone.now) boss = CharField(max_length=50) timedelta = IntegerField() city = CharField(max_length=40) def get_worker_time(self) -> datetime: """ Calculates worker's local time basing on timedelta :return: Worker's local datetime """ return datetime.now() + timedelta(hours=self.timedelta) def has_checked_in_today(self) -> bool: """ Checks if a worker has already created a checkin today :return: bool """ return DailyCheckin.objects.today_checkins(self).exists() def tg_verified(self) -> bool: return int(self.telegram_id or 0) > 0 def __repr__(self): return f"{self.id}) {self.full_name} - сотрудник на позиции {self.position} под руководством {self.boss}" def __str__(self): return self.__repr__()
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 DateTimeField fields = [DateTimeField()] else: from django.db.backends.util import typecast_timestamp 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: datetime = row[offset] if resolve_columns: datetime = self.resolve_columns(row, fields)[offset] elif needs_string_cast: datetime = typecast_timestamp(str(datetime)) # Datetimes are artifically returned in UTC on databases that # don't support time zone. Restore the zone used in the query. if settings.USE_TZ: datetime = datetime.replace(tzinfo=None) datetime = timezone.make_aware(datetime, self.query.tzinfo) yield datetime
class CommentLabelHistory(models.Model): grader = ForeignKey(User) ctime = DateTimeField(default=datetime.now()) grade = IntegerField() category = ForeignKey( LabelCategory) #so we can grade different dimensions of a post. comment = ForeignKey(Comment)
class Comment(models.Model): # old: nb2_comment TYPES = ((1, "Private"), (2, "Staff"), (3, "Class"), (4, "Tag Private")) location = ForeignKey(Location) # old: id_location integer parent = ForeignKey('self', null=True) # old: id_parent integer author = ForeignKey(User) # old: id_author integer, ctime = DateTimeField(default=datetime.now, db_index=True) # old: ctime timestamp body = TextField(blank=True, null=True) type = IntegerField(choices=TYPES) signed = BooleanField(default=True) # old: signed integer DEFAULT 0, deleted = BooleanField(default=False) # old: vis_status integer DEFAULT 0 moderated = BooleanField(default=False) def __unicode__(self): return "%s %s: %s " % (self.__class__.__name__, self.id, self.body[:50]) @property def created(self): if (timezone.is_naive(self.ctime)): return str( calendar.timegm(pytz.utc.localize(self.ctime).timetuple())) else: return str( calendar.timegm(self.ctime.astimezone(pytz.utc).timetuple()))
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 Membership(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) _id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=200, null=True, blank=True) subscribtionFee = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) monthlyFee = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) hasPersonalTrainingFee = models.BooleanField(default=False) personalTrainingFee = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) totalFee = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) beginingDate = DateTimeField(models.DateTimeField(auto_now_add=True)) #image = models.ImageField(null=True, blank=True) def __str__(self): return self.name
class Device(models.Model): human_readable = CharField(max_length=300, verbose_name='Идентификатор') is_active = BooleanField(default=True, verbose_name='Активен') ip_address = IPAddressField() fw_version = CharField(max_length=20, blank=True, verbose_name='Версия прошивки') last_queried = DateTimeField(default=datetime.datetime.now(), verbose_name='Время последнего опроса') query_status = CharField(max_length=20, blank=True, default='queue', verbose_name='Результат опроса', choices=[('queue', 'В очереди'), ('query', 'Опрашивается'), ('success', 'Успех'), ('failure', 'Ошибка')]) login = CharField(max_length=200) password = CharField(max_length=128) class Meta: verbose_name = u'Устройство' verbose_name_plural = u'Устройства' def __str__(self): return '%s@%s' % (self.human_readable, self.ip_address)
class Landing(models.Model): user = ForeignKey(User) ctime = DateTimeField(default=datetime.now) ip = CharField(max_length=63, blank=True, null=True) client = CharField(max_length=1023, blank=True, null=True) referer = CharField(max_length=1023, blank=True, null=True) path = CharField(max_length=1023, blank=True, null=True)
class TopUser(models.Model): user = models.ForeignKey(User) points = models.IntegerField() date_created = DateTimeField(u'fecha de calculo', auto_now_add=True) type = models.CharField( max_length=20, choices=[ ('WEEK', 'WEEK'), ('MONTH', 'MONTH'), ('YEAR', 'YEAR')])
class Note(Model): bookmark = ForeignKey(Bookmark, on_delete=models.CASCADE, related_name='notes') time = DateTimeField(auto_now_add=True, null=False, blank=True) text = TextField() def __str__(self): return self.text
class ClearPassLoginAttempt(Model): ACCEPT_RESULT = 0 REJECT_RESULT = 1 TIMEOUT_RESULT = 2 RESULT_CHOICES = ( (ACCEPT_RESULT, 'ACCEPT'), (REJECT_RESULT, 'REJECT'), (TIMEOUT_RESULT, 'TIMEOUT'), ) username = CharField(max_length=50, blank=True, null=True, db_index=True) time = DateTimeField() service = CharField(max_length=100) roles = ArrayField(CharField(max_length=50)) client_mac_address = MACAddressField(db_index=True) enforcement_profiles = ArrayField(CharField(max_length=100)) result = PositiveSmallIntegerField(choices=RESULT_CHOICES) clearpass_ip = GenericIPAddressField() alerts = TextField(null=True, blank=True) def __str__(self): return ('Username: '******', Service: ' + str(self.service) + ', Roles: ' + str(self.roles) + '\n') @cached_property def client_mac_address_formatted(self): from .utils import mac_address_with_colons # noqa return mac_address_with_colons(self.client_mac_address) class Meta: verbose_name = 'ClearPass Login Attempt'
class CommentLabel(models.Model): """Used for finer grain grading or categorizing comments or threads""" grader = ForeignKey(User) ctime = DateTimeField(default=datetime.now()) grade = IntegerField() category = ForeignKey(LabelCategory) #so we can grade different dimensions of a post. comment = ForeignKey(Comment)
class GuestLoginHistory(models.Model): """ Records the transition between a login as guest account and login as a exising account. This data supplements the one in GuestHistory. i.e. for the cases where we have a transition from a guest to a existing user. Note that SSO (i.e. Google ID) users are always considered "existing" even if they weren't in the DB before (since their guest account id doesn't get recycled), so they appear here. """ guest = ForeignKey(User, related_name="u1") user = ForeignKey(User, related_name="u2") ctime = DateTimeField(null=True, default=datetime.now())
class PageSeen(models.Model): source = ForeignKey(Source) page = IntegerField() session = ForeignKey(Session, null=True) user = ForeignKey( User, null=True) #duplicate (cf session) but inlined for performance ctime = DateTimeField(default=datetime.now)
def get_is_read(self, obj): request = self.context.get("request", None) if request: user = getattr(request, "user", None) if user: if obj.user == user: replies = obj.replies.exclude(user=user) if obj.read_at: return replies.filter(created_at__gt=obj.read_at).count() == 0 return replies.count() == 0 return obj.reception_set.filter( user=user, read_at__isnull=False ).annotate( latest_created_at=Max( Case( When( ~Q(message__replies__user=request.user), then='message__replies__created_at' ), default=Value(obj.created_at), output_field=DateTimeField() ) ) ).filter(Q(latest_created_at__isnull=True) | Q(read_at__gt=F('latest_created_at')), read_at__gt=obj.created_at).count() >= 1 return False
class Comment(models.Model): # old: nb2_comment TYPES = ((1, "Private"), (2, "Staff"), (3, "Class")) location = ForeignKey(Location) # old: id_location integer parent = ForeignKey('self', null=True) # old: id_parent integer author = ForeignKey(User) # old: id_author integer, ctime = DateTimeField(default=datetime.now) # old: ctime timestamp body = TextField(blank=True, null=True) type = IntegerField(choices=TYPES) signed = BooleanField(default=True) # old: signed integer DEFAULT 0, deleted = BooleanField(default=False) # old: vis_status integer DEFAULT 0 moderated = BooleanField(default=False) def __unicode__(self): return "%s %s: %s " % (self.__class__.__name__, self.id, self.body[:50]) @property def created(self): t_d = self.ctime.isocalendar() t_now = datetime.now().isocalendar() if t_d[0] != t_now[0]: #not even this year return self.ctime.strftime("%d %b %Y") if t_d[1] != t_now[1]: #this year but not this week return self.ctime.strftime("%d %b, %I:%M%p") if t_d[2] != t_now[2]: #this week but not today return self.ctime.strftime("%a %I:%M%p") #today: return self.ctime.strftime("%I:%M%p")
class Village(Model): id = IntegerField(verbose_name=_('village id'), primary_key=True, unique=True, blank=False, null=False) name = CharField(max_length=128, verbose_name=_('village name'), unique=True, blank=False, db_index=True) x = FloatField(verbose_name=_('coordinate x')) y = FloatField(verbose_name=_('coordinate y')) created = DateTimeField(verbose_name=_('created'), auto_now=True, auto_now_add=True) owner = ForeignKey(User, verbose_name=_('owner'), db_constraint=False, null=True, blank=True) def __unicode__(self): return u'[%000000000d] %s' % (self.id, self.name) class Meta: verbose_name = _('village') verbose_name_plural = _('villages') unique_together = (('x', 'y'), ) index_together = (('x', 'y'), )
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 User(AbstractBaseUser, PermissionsMixin, SerializationMixin): """User model.""" USERNAME_FIELD = 'email' REQUIRED_FIELDS = () objects = UserManager() email = LowercaseEmailField(unique=True, error_messages=MESSAGES) is_email_verified = BooleanField(default=False) is_active = BooleanField(default=True) is_staff = BooleanField(default=False) is_superuser = BooleanField(default=False) date_joined = DateTimeField(default=datetime.now, editable=False) balance = IntegerField(default=0) password_reset_code = IntegerField(null=True, blank=True) password_reset_request_time = DateTimeField(null=True, blank=True) device = ForeignKey( Device, related_name='owner', null=True, on_delete=CASCADE ) @property def profile(self): try: return self._profile except Profile.DoesNotExist: return Profile.objects.create(user=self) def __str__(self): if self.profile.full_name: return f"{self.email} ({self.profile.full_name})" return self.email def has_perm(self, _perm, _obj=None): return self.is_staff def has_module_perms(self, _app_label): return self.is_staff def clean(self): super().clean() self.email = User.objects.normalize_email(self.email) def notify(self, **kwargs): if self.device.is_active: self.device.send_push_notification(**kwargs)
class Comment(models.Model): """ Object representing a comment on a blog post """ author = CharField(max_length=255) timestamp = DateTimeField() content = CharField(max_length=255)
class Comment(models.Model): article=models.ForeignKey(Article,related_name="comments",on_delete=models.CASCADE) name=models.CharField(max_length=200) body=models.TextField() date=DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.article.title,self.date.strftime("%Y-%m-%d %H:%M"))
class Message(Model): sender = ForeignKey(User, related_name='messages', null=True) room = ForeignKey(Room, related_name='messages') message = TextField() timestamp = DateTimeField(db_index=True, auto_now_add=True) def __str__(self): return '<Message - %s>' % self.message
class Comentario(models.Model): post = models.ForeignKey(Redaccion, related_name='comentarios', on_delete=models.CASCADE) nombre = models.CharField(max_length=255) cuerpo = models.TextField() fecha_comentario = DateTimeField(auto_now_add=True) def __str__(self): return self.nombre
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) ExtractYear.register_lookup(YearExact) ExtractYear.register_lookup(YearGt) ExtractYear.register_lookup(YearGte) ExtractYear.register_lookup(YearLt) ExtractYear.register_lookup(YearLte) ExtractIsoYear.register_lookup(YearExact) ExtractIsoYear.register_lookup(YearGt) ExtractIsoYear.register_lookup(YearGte) ExtractIsoYear.register_lookup(YearLt) ExtractIsoYear.register_lookup(YearLte)
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) DateTimeField.register_lookup(SecondTransform)
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:
def main(filename, username): user = User.objects.get(username=username) json = cjson.decode(open(filename).read()) json_index = 0 types = defaultdict(list) # Organize the JSON dump by model type for item in json: types[item['model']].append(item) # Rebuild the models in the necessary order # Languages and associated models first languages = dict() for language in types.get('drills.language', []): languages[language['pk']] = Language(name=language['fields']['name'], module_name=language['fields']['module_name']) languages[language['pk']].save() declensions = dict() for d in types.get('drills.declension', []): declensions[d['pk']] = Declension(name=d['fields']['name'], language=languages[d['fields']['language']]) declensions[d['pk']].save() for case in types.get('drills.case', []): x = Case(name=case['fields']['name'], language=languages[case['fields']['language']]) x.save() for number in types.get('drills.number', []): x = Number(name=number['fields']['name'], language=languages[number['fields']['language']]) x.save() for gender in types.get('drills.gender', []): x = Gender(name=gender['fields']['name'], language=languages[gender['fields']['language']]) x.save() declinabletypes = dict() for dt in types.get('drills.declinabletype', []): declinabletypes[dt['pk']] = DeclinableType(name=dt['fields']['name'], language=languages[dt['fields']['language']]) declinabletypes[dt['pk']].save() conjugations = dict() for c in types.get('drills.conjugation', []): conjugations[c['pk']] = Conjugation(name=c['fields']['name'], language=languages[c['fields']['language']]) conjugations[c['pk']].save() for person in types.get('drills.person', []): x = Person(name=person['fields']['name'], language=languages[person['fields']['language']]) x.save() for tense in types.get('drills.tense', []): x = Tense(name=tense['fields']['name'], language=languages[tense['fields']['language']]) x.save() for voice in types.get('drills.voice', []): x = Voice(name=voice['fields']['name'], language=languages[voice['fields']['language']]) x.save() for mood in types.get('drills.mood', []): x = Mood(name=mood['fields']['name'], language=languages[mood['fields']['language']]) x.save() # Then users (TODO) # Then word lists and tags wordlists = dict() for wordlist in types.get('drills.wordlist', []): wordlists[wordlist['pk']] = WordList(user=user, name=wordlist['fields']['name'], language=languages[wordlist['fields']['language']]) wordlists[wordlist['pk']].save() now = datetime.now() tags = dict() for tag in types.get('drills.tag', []): args = dict() args['wordlist'] = wordlists[tag['fields']['wordlist']] args['name'] = tag['fields']['name'] tags[tag['pk']] = Tag(**args) tags[tag['pk']].save() # Now words words = dict() for word in types.get('drills.word', []): word_pk = word['pk'] word = word['fields'] args = dict() args['wordlist'] = wordlists[word['wordlist']] args['word'] = word['word'] args['definition'] = word['definition'] args['date_entered'] = word.get('date_entered', now) args['last_reviewed'] = word.get('last_reviewed', now) args['last_wrong'] = word.get('last_wrong', now) # Try to handle the old "average_difficulty" field gracefully if 'average_difficulty' in word: difficulty = word['average_difficulty'] if difficulty < 1: memory_index = 9 elif difficulty < 2: memory_index = 8 elif difficulty < 5: memory_index = 7 elif difficulty < 10: memory_index = 6 elif difficulty < 20: memory_index = 5 elif difficulty < 25: memory_index = 4 elif difficulty < 30: memory_index = 3 else: memory_index = 0 args['memory_index'] = memory_index # HACK! This is to get a datetime object without having to parse # the string myself. hack = DateTimeField() last_reviewed = hack.to_python(args['last_reviewed']) args['next_review'] = (last_reviewed + Word.REVIEW_PERIODS[memory_index][1]) else: args['memory_index'] = word.get('memory_index', 0) args['next_review'] = word.get('next_review', now) args['review_count'] = word.get('review_count', 0) words[word_pk] = Word(**args) words[word_pk].save() for tag_id in word['tags']: w.tags.add(tags[tag_id]) # Verbs for verb in types.get('drills.verb', []): verb = verb['fields'] args = dict() args['wordlist'] = wordlists[verb['wordlist']] args['conjugation'] = conjugations[verb['conjugation']] args['word'] = words[verb['word']] v = Verb(**args) v.save() # Declinable words for dw in types.get('drills.declinableword', []): dw = dw['fields'] args = dict() args['wordlist'] = wordlists[dw['wordlist']] args['declension'] = declensions[dw['declension']] args['type'] = declinabletypes[dw['type']] args['word'] = words[dw['word']] d = DeclinableWord(**args) d.save() # And finally the stats (TODO) transaction.commit()
def parse_date(s): from django.db.models.fields import DateTimeField dtf = DateTimeField() return dtf.to_python(s)