class Server(models.Model): """ 服务器信息 """ raid_choices = Choices('RAID5', 'RAID0', 'RAID1', 'RAID10', 'RAID6', 'DIRECT') type_choices = Choices('CLOUD', 'ENTITY', 'VMSYSTEM') asset = models.OneToOneField('Asset') s_type = StatusField('服务器类型', choices_name='type_choices') hostname = models.CharField(u'主机名称', max_length=128, unique=True) raid = StatusField(u'raid卡', choices_name='raid_choices', null=True, blank=True) os_platform = models.CharField(u'系统', max_length=16, null=True, blank=True) os_version = models.CharField(u'系统版本', max_length=16, null=True, blank=True) int_ip = models.GenericIPAddressField(u'内网IP', max_length=64, blank=True, null=True) ext_ip = models.GenericIPAddressField(u'外网IP', max_length=64, blank=True, null=True) note = models.CharField(u'备注', max_length=128, null=True, blank=True) class Meta: verbose_name_plural = u"服务器表" def __str__(self): return '%s - %s' % (self.asset, self.hostname)
class Inference(models.Model): """Training result information obtained once deployed a model""" INPUT_FORMAT = Choices('RAW', 'AVRO') STATUS = Choices('deployed', 'stopped') """Sets its default value to the first item in the STATUS choices:""" status = StatusField() status_changed = MonitorField(monitor='status') model_result = models.ForeignKey(TrainingResult, null=True, related_name='inferences', on_delete=models.SET_NULL) replicas = models.IntegerField(default=1) input_format = StatusField(choices_name='INPUT_FORMAT') input_config = models.TextField(blank=True) input_topic = models.TextField(blank=True) output_topic = models.TextField(blank=True) time = models.DateTimeField(default=now, editable=False) limit = models.DecimalField(max_digits=15, decimal_places=10, blank=True, null=True) output_upper = models.TextField(blank=True) class Meta(object): ordering = ('-time', )
class Thing(BaseModel): name = models.CharField(max_length=256) slug = AutoSlugField(populate_from=['name'], max_length=256) owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='things', null=True, blank=True ) STATUS = Choices('draft', 'published') status = StatusField(choices_name='STATUS') KINDS = Choices('cake', 'cookie', 'candy') kind = StatusField(choices_name='KINDS') tags = TaggableManager(through='helpers.GenericSimpleflakeIDTaggedItem') class Meta: db_table = 'things' def __str__(self): return self.slug def is_owned_by(self, user): return self.owner == user
class Organization(models.Model): STATES = STATES ORG_TYPE = ORG_TYPE PARTY = PARTY name = models.CharField(max_length=1024, verbose_name="Organization Name") state = StatusField(choices_name='STATES', db_index=True) website = models.CharField(max_length=1024, blank=True, verbose_name="Company Website") org_type = StatusField(choices_name='ORG_TYPE', db_index=True) endorses = models.BooleanField(default=False) political_party = StatusField(choices_name='PARTY', db_index=True)
class Donation(models.Model): STATUS_OPTIONS = Choices('pending', 'accepted', 'declined') name = models.TextField(max_length=30, blank=True) text_description = models.TextField(max_length=500, blank=True) quantity = models.IntegerField(default=0, null=True) img_link = models.URLField(max_length=200, blank=True) city = models.TextField(max_length=30, blank=True) donor = models.ForeignKey(User, related_name='donation_creator', on_delete=models.CASCADE) donor_email = models.EmailField(max_length=255) status = StatusField(choices_name='STATUS_OPTIONS', default='pending') owner_interest = models.BooleanField(default=False) needs_pickup = models.BooleanField(default=False) declined_reason = models.TextField(max_length=200, blank=True, default='', null=True) business = models.ForeignKey(Business, on_delete=models.CASCADE) @staticmethod def get_my_donations(user): donation_list = list(user.donation_creator.all()) return donation_list @staticmethod def get_all_business_donations(user, business_in): donation_list = list(Donation.objects.filter(business=business_in)) return donation_list
class FlexUser(AbstractUser): """A college's member""" code = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) school = models.ForeignKey(School, on_delete=models.CASCADE, null=True) sur_name = models.CharField(max_length=100, null=True) avatar = models.ImageField(default="avatars/default.webp", upload_to="avatars") STATUS = Choices('Admin', 'Teacher', 'Student') status = StatusField(choices_name='STATUS') change_limit = models.DateField(default=timezone.now) def __str__(self): return f'{self.username} ({self.fullname})' @property def fullname(self): return f'{self.last_name} {self.first_name} {self.sur_name}' @property def photo(self): return f'{self.avatar}' @property def registered(self): return self.date_joined.date() def change_active(self): self.is_active = False self.save(update_fields=['is_active'])
class NewsStory(models.Model): STAGES = Choices('Unpublished', 'Published') stage = StatusField(choices_name='STAGES') candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name="news") title = models.CharField(max_length=255, blank=True) teaser = RichTextField(blank=True) link = models.CharField(max_length=255, blank=True) image = models.ImageField(blank=True) date = models.DateField(blank=True) objects = NewsStoryQueryset.as_manager() class Meta: verbose_name_plural = "News Stories" def __str__(self): return self.title @property def meta(self): if self.date: return True @property def image_url(self): if self.image: return self.image.url return None
class Organization(DjangoOrganization, TimeStampedModel): # Stripe data subscription_stripe_customer_id = models.CharField(max_length=255, default="") subscription_stripe_checkout_session_id = models.CharField( max_length=255, default="" ) subscription_stripe_subscription_id = models.CharField(max_length=255, default="") # Subscription data SUBSCRIPTION_CHOICES = Choices("free", "basic") subscription_type = StatusField(choices_name="SUBSCRIPTION_CHOICES", default="free") # Differs from the creation date of the organization, tracks when the subscription is changed subscription_date = MonitorField(monitor="subscription_type") # Organization data contact_email = models.EmailField(max_length=254, unique=True) description = models.TextField() currency = models.CharField( choices=CURRENCY_CHOICES, default=CURRENCY_CHOICES.euro, max_length=255 ) @property def stats(self): # TODO: fix circulair import # To prevent a circular import reference, we import these here from organization.models.inventory import Product, Location, Mutation return { "product_count": Product.objects.for_organization(self).count(), "location_count": Location.objects.for_organization(self).count(), "mutation_count": Mutation.objects.for_organization(self).count(), } def __str__(self): return self.name
class Siniestro(models.Model): STATUS = Choices('a_confirmar', 'confirmado', 'reportado') status = StatusField() causa_principal = models.ForeignKey('Causa') fecha = models.DateField() hora = models.TimeField(null=True) lugar = models.CharField(max_length=200, help_text='La dirección aproximada del siniestro. Ej: Ruta 5, Km 123') provincia = models.CharField(max_length=20, choices=PROVINCE_CHOICES) posicion = GeopositionField() mensaje = models.TextField(null=True) referencias_prensa = models.ManyToManyField('ReferenciaPrensa') cargado_por = models.ForeignKey('auth.User', editable=False, null=True) @property def geom(self): return { 'type': 'Point', 'coordinates': [ float(self.posicion.longitude), float(self.posicion.latitude) ] } def __str__(self): return "{} ({})".format(self.causa_principal, self.get_provincia_display())
class Fragment(Commentable, Votable, models.Model): STATUS = Choices('OPEN', 'CLOSED') user = models.ForeignKey( User, on_delete=models.CASCADE, ) title = models.CharField(max_length=256) content = models.CharField(max_length=2048) tags = models.ManyToManyField(Tag) status = StatusField(choices=STATUS, default=STATUS.OPEN) date_created = models.DateTimeField(auto_now_add=True, editable=False) date_modified = models.DateTimeField(auto_now=True, editable=False) date_closed = MonitorField(monitor='status', when=[STATUS.CLOSED], default=None, null=True, blank=True, editable=False) def __str__(self): return f"{ self.pk } { self.title[:10] if len(self.title) > 10 else self.title }" def get_answer_count(self): return self.answer_set.count()
class Recording(models.Model): STATUS = Choices('Published', 'Hidden') FILTER_STATUS = STATUS + ['None'] media_file = models.OneToOneField('multimedia.MediaFile', related_name='recording') event = models.ForeignKey(Event, related_name='recordings') title = models.CharField(max_length=150, blank=True) set_number = models.IntegerField(default=1) state = StatusField(default=STATUS.Published) date_added = models.DateTimeField(auto_now_add=True) view_count = models.PositiveIntegerField(default=0) objects = RecordingManager() class Meta: ordering = ['set_number'] def is_published(self): return self.state == self.STATUS.Published def is_valid_status(self, status): return status in self.STATUS or status == "None" def get_redirect_url(self): """ Redirect view used to track media using jwplayer analytics in a way that they have a consistent URL and not have the S3 access key. """ return reverse('media_redirect', kwargs={'recording_id': self.id})
class TenantSpecificFieldDefinition(SingleTenantModelMixin): name = models.CharField(max_length=255) DATA_TYPES = Choices('char', 'text', 'integer', 'float', 'datetime', 'date') data_type = StatusField(choices_name='DATA_TYPES') is_required = models.BooleanField(default=False) default_value = models.TextField() validators = models.ManyToManyField('TenantSpecificFieldsValidator', blank=True) table_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) table_id = models.PositiveIntegerField(blank=True, null=True) class Meta: unique_together = [('tenant', 'table_id', 'table_content_type', 'name') ] def __str__(self): content_type = '%s/%s' % (self.tenant.slug, str( self.table_content_type)) if content_type == 'shared_schema_tenants.TenantSpecificTable': content_type = str(self.table) return '%s.%s' % (content_type, self.name)
class Project(models.Model): maintainer = models.ForeignKey(PisiUser, on_delete=models.DO_NOTHING, related_name='%(class)s_project_leader') contributors = models.ManyToManyField( PisiUser, related_name='%(class)s_project_participant') repos = models.ManyToManyField(Repository) STATUS = Choices('abandoned', 'in development', 'maintained', 'on draft', 'complete') status = StatusField() progress = models.IntegerField(default=0, validators=[ MinValueValidator(COMPLETION_ZERO), MaxValueValidator(COMPLETION_DONE) ]) vacant_slots = models.IntegerField( default=0, validators=[MinValueValidator(0), MaxValueValidator(128)]) VISIBILITY_CHOICES = ( (1, _("Public")), (2, _("Private")), ) visibility = models.SmallIntegerField(choices=VISIBILITY_CHOICES, default=1)
class Take(models.Model): name = models.CharField(max_length=200) shot = models.ForeignKey(Shot, on_delete=models.CASCADE, related_name='takes') capture_time = models.DateTimeField('capture time', auto_now_add=True) sequence = models.IntegerField(default=1) export_path = models.CharField(max_length=250, null=True, blank=True) video_thumb = models.CharField(max_length=250, null=True, blank=True) FLAG = Choices('none', 'best', 'bad', 'calib') flag = StatusField(choices_name='FLAG', default='none') def has_write_access(self, user): # TODO Access rights return user.is_superuser def total_size(self): return self.cameras.all().aggregate( Sum('total_size'))['total_size__sum'] def full_name(self): return '%s/%s' % (self.name, self.shot.full_name()) def __str__(self): return '#%d' % (self.id)
class Agenda(Act): """ Maps the *Ordine del Giorno* act type. It is a political act, used to publicly influence the following discussions on Deliberations. It is specifically used with respect to issues specific to the deliberation process. It is submitted to the Council approval and Emendations to it can be presented before the votation. """ FINAL_STATUSES = ( ('APPROVED', _('approved')), ('REJECTED', _('rejected')), ) STATUS = Choices( ('PRESENTED', 'presented', _('presented')), ('COUNCIL', 'council', _('council')), ('APPROVED', 'approved', _('approved')), ('REJECTED', 'rejected', _('rejected')), ) status = StatusField() class Meta: verbose_name = _('agenda') verbose_name_plural = _('agenda') @models.permalink def get_absolute_url(self): return ('om_agenda_detail', (), {'pk': str(self.pk)})
class Motion(Act): """ It is a political act, used to publicly influence members of the City Government, or the Mayor, on a broad type of issues (specific to the Comune proceedings, or of a more general category) It is submitted to the Council approval and Emendations to it can be presented before the votation. """ FINAL_STATUSES = ( ('APPROVED', _('approved')), ('REJECTED', _('rejected')), ) STATUS = Choices( ('PRESENTED', 'presented', _('presented')), ('COUNCIL', 'council', _('council')), ('APPROVED', 'approved', _('approved')), ('REJECTED', 'rejected', _('rejected')), ) status = StatusField() class Meta: verbose_name = _('motion') verbose_name_plural = _('motions') @models.permalink def get_absolute_url(self): return ('om_motion_detail', (), {'pk': str(self.pk)})
class Company(Organization): "Company's general information" user = models.ForeignKey(User) #name = models.CharField(max_length=128) description = models.TextField(blank=True, max_length=250) #slug = AutoSlugField(populate_from='name', unique_with='id', null=True) website = models.URLField(max_length=200, blank=True) address_line1 = models.CharField(max_length=100) address_line2 = models.CharField(blank=True, max_length=100) city = models.CharField(max_length=50) state_province = models.CharField(max_length=50, blank=True) postal_code = models.CharField(max_length=50) country = CountryField() STATUS = Choices ( 'Chemical', 'Mining', 'Food', 'Basic Materials', 'Services', 'Transportation', 'Healthcare', 'Technology', 'Communication', 'manufacturing' ) industry = StatusField(default=STATUS.manufacturing) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __unicode__(self): return self.name
class User(AbstractUser): STATUS = Choices('1', '2') level = StatusField() # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) def profile_image_url(self): # Set your variables here default = None size = 100 fb_uid = SocialAccount.objects.filter(user_id=self.id, provider='facebook') if len(fb_uid): return "http://graph.facebook.com/{}/picture?width={}&height={}".format( fb_uid[0].uid, size, size) # construct the url gravatar_url = "https://www.gravatar.com/avatar/" + hashlib.md5( self.email.lower().encode('utf-8')).hexdigest() + "?" gravatar_url += urlencode({'d': default, 's': str(size)}) return gravatar_url
class VisionSyncInfo(models.Model): STATUS = Choices('SUCCESS', 'FAILURE', 'NOT_RUNNING') sync_date = models.DateTimeField(auto_now_add=True) sync_status = StatusField(default=STATUS.NOT_RUNNING) start_date = models.DateField(null=True) end_date = models.DateField(null=True) is_daily_sync = models.BooleanField(default=True) def set_sync_status_success(self): return self._set_sync_status(VisionSyncInfo.STATUS.SUCCESS) def set_sync_status_failure(self): return self._set_sync_status(VisionSyncInfo.STATUS.FAILURE) def _set_sync_status(self, status): self.sync_status = status self.save() return self @staticmethod def new_instance(is_daily_sync, start_date, end_date): return VisionSyncInfo.objects.create(is_daily_sync=is_daily_sync, start_date=start_date, end_date=end_date) @staticmethod def get_daily_sync_start_date(): if not VisionSyncInfo.objects.filter(is_daily_sync=True).count(): last_sync_info = VisionSyncInfo.objects.filter( is_daily_sync=False).order_by('-sync_date', '-id').first() return last_sync_info.end_date if last_sync_info else VisionSyncInfo.get_manual_sync_start_date( ) last_sync_info = VisionSyncInfo.objects.filter( is_daily_sync=True).order_by('-sync_date', '-id').first() sync_start_date = last_sync_info.end_date if last_sync_info.sync_status == VisionSyncInfo.STATUS.SUCCESS \ else last_sync_info.start_date return sync_start_date @staticmethod def get_daily_sync_end_date(): return datetime.date.today() @staticmethod def get_manual_sync_start_date(): system_settings = SystemSettings.objects.first() sync_start_date = system_settings.sync_start_date if system_settings else None return sync_start_date if sync_start_date else None @staticmethod def get_manual_sync_end_date(): return datetime.date.today() @staticmethod def get_last_manual_sync_status(): sync_info = VisionSyncInfo.objects.filter( is_daily_sync=False).order_by('-sync_date', '-id').first() return sync_info.sync_status if sync_info else None
class Questionnaire(BaseModel): DRAFT = 'draft' PUBLISHED = 'published' FINALIZED = 'finalized' STATUS = Choices(FINALIZED, PUBLISHED, DRAFT) name = models.CharField(max_length=256, null=False, blank=False) description = models.TextField(null=True, blank=True) year = models.PositiveIntegerField(null=True, blank=True) status = StatusField(choices_name="STATUS", default=DRAFT) def __unicode__(self): return '%s' % self.name def sub_sections(self): sections = self.sections.all() from questionnaire.models import SubSection return SubSection.objects.filter(section__in=sections) def get_all_questions(self): all_questions = [] for subsection in self.sub_sections(): all_questions.extend(subsection.all_questions()) return all_questions def all_groups(self): all_groups = [] for subsection in self.sub_sections(): all_groups.extend(subsection.question_group.all()) return all_groups
class Project(models.Model): STATUS = Choices('Active', 'Inactive') name = models.CharField(max_length=100) github_url = models.CharField(max_length=200) version = models.CharField(max_length=300) database = models.CharField(max_length=300, blank=True) slug = models.SlugField(max_length=40, editable=False, blank=True, null=True) status = StatusField(default=STATUS.Inactive) default_username = models.CharField(max_length=30, blank=True) default_password = models.CharField(max_length=30, blank=True) survey_form_url = models.URLField(blank=True) class Meta: ordering = ['name'] def __unicode__(self): return self.name def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Project, self).save(*args, **kwargs) def cartridges_list(self): complete_list = self.version if self.database: complete_list += ("," + self.database) return [v.strip() for v in complete_list.split(',')] def landing_page_url(self): return reverse('landing_page', kwargs={'slug': self.slug})
class StatusModel(models.Model): """ An abstract base class model with a ``status`` field that automatically uses a ``STATUS`` class attribute of choices, a ``status_changed`` date-time field that records when ``status`` was last modified, and an automatically-added manager for each status that returns objects with that status only. """ status = StatusField(_("status")) status_changed = MonitorField(_("status changed"), monitor="status") def save(self, *args, **kwargs): """ Overriding the save method in order to make sure that status_changed field is updated even if it is not given as a parameter to the update field argument. """ update_fields = kwargs.get("update_fields", None) if update_fields and "status" in update_fields: kwargs["update_fields"] = set(update_fields).union( {"status_changed"}) super().save(*args, **kwargs) class Meta: abstract = True
class Interpellation(Act): """ WRITEME """ ANSWER_TYPES = Choices( ('WRITTEN', 'written', _('Written')), ('VERBAL', 'verbal', _('Verbal')), ) STATUS = Choices(('PRESENTED', 'presented', _('presented')), ('ANSWERED', 'answered', _('answered')), ('NOTANSWERED', 'notanswered', _('not answered'))) status = StatusField() answer_type = models.CharField(_('answer type'), max_length=8, choices=ANSWER_TYPES) question_motivation = models.TextField(blank=True) answer_text = models.TextField(blank=True) class Meta: verbose_name = _('interpellation') verbose_name_plural = _('interpellations') @models.permalink def get_absolute_url(self): return ('om_interpellation_detail', (), {'pk': str(self.pk)})
class Request(models.Model): STATUS_OPTIONS = Choices('sent', 'received') name = models.TextField(max_length=30, blank=True) text_description = models.TextField(max_length=500, blank=True) inquirer = models.ForeignKey(User, related_name='request_creator', on_delete=models.CASCADE) user_email = models.EmailField(max_length=255) status = StatusField(choices_name='STATUS_OPTIONS', default='sent') declined_reason = models.TextField(max_length=200, blank=True, default='', null=True) business = models.ForeignKey(Business, on_delete=models.CASCADE) @staticmethod def get_my_requests(user): request_list = list(user.request_creator.all()) return request_list @staticmethod def get_all_business_requests(user, business_in): request_list = list(Request.objects.filter(business=business_in)) return request_list
class EmailMessage(Base): STATUS = Choices(_('Created'), _('Scheduled'), _('Sent'), _('Opened'), _('Clicked')) status = StatusField(verbose_name=_('Status')) widget = models.ForeignKey('widgets.Widget', null=True) leed = models.ForeignKey('widgets.Leed', null=True) subject = models.CharField(max_length=50, null=True) text = models.CharField(max_length=500, null=True) html = models.CharField(max_length=1000, null=True) status_changed = MonitorField(monitor='status') scheduled_at = MonitorField(monitor='status', when=['Sent'], verbose_name=_('Email scheduled at')) sent_at = MonitorField(monitor='status', when=['Scheduled'], verbose_name=_('Email sent at')) opened_at = MonitorField(monitor='status', when=['Opened'], verbose_name=_('Email opened at')) clicked_at = MonitorField(monitor='status', when=['Clicked'], verbose_name=_('Email clicked at')) def get_absolute_url(self): return reverse('widgets:email_detail', kwargs={'pk': self.pk})
class Page(models.Model): STATUS = Choices('active', 'deleted') status = StatusField() project = models.ForeignKey(Project, related_name='pages') listed = models.ManyToManyField( 'Page', related_name='listed_by', blank=True) title = models.CharField(max_length=64) slug = models.SlugField(editable=False) content = models.TextField() html = models.TextField(blank=True) objects = UserFilteringManager() def save(self, *args, **kwargs): self.html = markdown.compile(self.content, context={ 'namespace': self.project.namespace.name, 'project': self.project.name, 'page': self.slug}) self.slug = slugify(self.title) super(Page, self).save(*args, **kwargs) @classmethod def is_visible_q(cls, user): if user.is_superuser: return Q() return add_prefix('project', Project.is_visible_q(user)) & ( Q(status='active') | cls.is_visible_if_hidden_q(user) ) @staticmethod def is_visible_if_hidden_q(user): if user.is_anonymous(): return Q() return ~Q(status='deleted') & add_prefix('project', Project.is_visible_if_hidden_q(user)) def get_absolute_url(self): if self.slug == 'home': return reverse('projects-detail', kwargs=dict( namespace=self.project.namespace.name, project=self.project.name )) else: return reverse('projects-pages-detail', kwargs=dict( namespace=self.project.namespace.name, project=self.project.name, page=self.slug )) def __str__(self): return '\'%s\' in project %s' % (self.title, self.project) class Meta: unique_together = ( ('project', 'slug'), ('project', 'title') )
class TrainingResult(models.Model): """Training result information obtained once deployed a model""" STATUS = Choices('created', 'deployed', 'stopped', 'finished') """Sets its default value to the first item in the STATUS choices:""" status = StatusField() status_changed = MonitorField(monitor='status') deployment = models.ForeignKey(Deployment, default=None, related_name='results', on_delete=models.CASCADE) model = models.ForeignKey(MLModel, related_name='trained', on_delete=models.CASCADE) train_loss = models.DecimalField(max_digits=15, decimal_places=10, blank=True, null=True) train_metrics = models.TextField(blank=True) val_loss = models.DecimalField(max_digits=15, decimal_places=10, blank=True, null=True) val_metrics = models.TextField(blank=True) trained_model = models.FileField(upload_to=settings.TRAINED_MODELS_DIR, blank=True) class Meta(object): ordering = ('-status_changed', )
class StatusModel(models.Model): """ An abstract base class model with a ``status`` field that automatically uses a ``STATUS`` class attribute of choices, a ``status_changed`` date-time field that records when ``status`` was last modified, and an automatically-added manager for each status that returns objects with that status only. """ status = StatusField(_('status')) status_changed = MonitorField(_('status changed'), monitor='status') def save(self, *args, **kwargs): """ Overriding the save method in order to make sure that status_changed field is updated even if it is not given as a parameter to the update field argument. """ if ('update_fields' in kwargs and 'status' in kwargs['update_fields'] and 'status_changed' not in kwargs['update_fields']): kwargs['update_fields'] += ['status_changed'] super().save(*args, **kwargs) class Meta: abstract = True
class Project(models.Model): owner = models.ForeignKey('users.User', related_name='%(class)s_owner_relation') name = models.CharField(max_length=128, unique=True) slug = AutoSlugField(populate_from='name', unique_with='name') description = models.TextField() website = models.URLField(blank=True) # If accessible to everyone or only owner STATUS = Choices('Public', 'Private') status = StatusField() # See this for background: # http://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add/1737078#1737078 created = models.DateTimeField(editable=False) modified = models.DateTimeField() def save(self, *args, **kwargs): # On save, update timestamps if not self.id: self.created = datetime.datetime.today() self.modified = datetime.datetime.today() return super(Project, self).save(*args, **kwargs) def __unicode__(self): return self.name def get_absolute_url(self): return reverse('project:detail', kwargs={'slug': self.slug})
class Identificacion(TimeStampedModel): """ Es el modelo que guarda clasificaciones de actas para asociarlas a mesas """ STATUS = Choices('identificada', 'problema') status = StatusField(choices_name='STATUS', choices=STATUS) SOURCES = Choices('web', 'csv', 'telegram') source = StatusField(choices_name='SOURCES', default=SOURCES.web) fiscal = models.ForeignKey('fiscales.Fiscal', blank=True, on_delete=models.CASCADE) mesa = models.ForeignKey('elecciones.Mesa', related_name='identificaciones', null=True, blank=True, on_delete=models.SET_NULL) attachment = models.ForeignKey(Attachment, related_name='identificaciones', on_delete=models.CASCADE) # Se utiliza para permitir concurrencia entre consolidadores. tomada_por_consolidador = models.DateTimeField(default=None, null=True, blank=True) procesada = models.BooleanField(default=False) invalidada = models.BooleanField(default=False) def __str__(self): return ( f'id: {self.id} - {self.status} - {self.mesa} - {self.fiscal} - ' f'procesada: {self.procesada} - invalidada: {self.invalidada}') def invalidar(self): logger.info('Identificación invalidada', id=self.id) self.invalidada = True self.procesada = False self.save(update_fields=['invalidada', 'procesada']) def save(self, *args, **kwargs): """ Si el fiscal es troll, la identificación nace invalidada y ya procesada. """ if self.id is None and self.fiscal is not None and self.fiscal.troll: self.invalidada = True self.procesada = True super().save(*args, **kwargs)
def test_no_check_for_status(self): field = StatusField(no_check_for_status=True) # this model has no STATUS attribute, so checking for it would error field.prepare_class(Article)