class NormaJuridica(models.Model): ESFERA_FEDERACAO_CHOICES = Choices( ('M', 'municipal', _('Municipal')), ('E', 'estadual', _('Estadual')), ('F', 'federal', _('Federal')), ) texto_integral = models.FileField( blank=True, null=True, upload_to=norma_upload_path, verbose_name=_('Texto Integral'), validators=[restringe_tipos_de_arquivo_txt]) tipo = models.ForeignKey(TipoNormaJuridica, on_delete=models.PROTECT, verbose_name=_('Tipo da Norma Jurídica')) materia = models.ForeignKey(MateriaLegislativa, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_('Matéria')) numero = models.CharField(max_length=8, verbose_name=_('Número')) ano = models.PositiveSmallIntegerField(verbose_name=_('Ano'), choices=RANGE_ANOS) esfera_federacao = models.CharField(max_length=1, verbose_name=_('Esfera Federação'), choices=ESFERA_FEDERACAO_CHOICES) data = models.DateField(blank=False, null=True, verbose_name=_('Data')) data_publicacao = models.DateField(blank=True, null=True, verbose_name=_('Data de Publicação')) veiculo_publicacao = models.CharField( max_length=30, blank=True, verbose_name=_('Veículo de Publicação')) pagina_inicio_publicacao = models.PositiveIntegerField( blank=True, null=True, verbose_name=_('Pg. Início')) pagina_fim_publicacao = models.PositiveIntegerField( blank=True, null=True, verbose_name=_('Pg. Fim')) ementa = models.TextField(verbose_name=_('Ementa')) indexacao = models.TextField(blank=True, verbose_name=_('Indexação')) observacao = models.TextField(blank=True, verbose_name=_('Observação')) complemento = models.NullBooleanField(blank=True, verbose_name=_('Complementar ?'), choices=YES_NO_CHOICES) # XXX was a CharField (attention on migrate) assuntos = models.ManyToManyField(AssuntoNorma, blank=True, verbose_name=_('Assuntos')) data_vigencia = models.DateField(blank=True, null=True, verbose_name=_('Data Fim Vigência')) timestamp = models.DateTimeField(null=True) texto_articulado = GenericRelation(TextoArticulado, related_query_name='texto_articulado') data_ultima_atualizacao = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_('Data')) autores = models.ManyToManyField(Autor, through='AutoriaNorma', through_fields=('norma', 'autor'), symmetrical=False) norma_de_destaque = models.BooleanField( verbose_name=_('Norma de Destaque ?'), choices=YES_NO_CHOICES, default=False) apelido = models.TextField(blank=True, verbose_name=_('Apelido')) class Meta: verbose_name = _('Norma Jurídica') verbose_name_plural = _('Normas Jurídicas') ordering = ['-data', '-numero'] def get_normas_relacionadas(self): principais = NormaRelacionada.objects.filter( norma_principal=self.id).order_by('norma_principal__data', 'norma_relacionada__data') relacionadas = NormaRelacionada.objects.filter( norma_relacionada=self.id).order_by('norma_principal__data', 'norma_relacionada__data') return (principais, relacionadas) def get_anexos_norma_juridica(self): anexos = AnexoNormaJuridica.objects.filter(norma=self.id) return anexos def __str__(self): return _('%(tipo)s nº %(numero)s de %(data)s') % { 'tipo': self.tipo, 'numero': self.numero, 'data': defaultfilters.date(self.data, "d \d\e F \d\e Y") } @property def epigrafe(self): return _('%(tipo)s nº %(numero)s de %(data)s') % { 'tipo': self.tipo, 'numero': self.numero, 'data': defaultfilters.date(self.data, "d \d\e F \d\e Y") } def delete(self, using=None, keep_parents=False): if self.texto_integral: self.texto_integral.delete() return models.Model.delete(self, using=using, keep_parents=keep_parents) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.pk and self.texto_integral: texto_integral = self.texto_integral self.texto_integral = None models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields) self.texto_integral = texto_integral return models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
class Series(GcdData): class Meta: app_label = 'gcd' ordering = ['sort_name', 'year_began'] # Core series fields. name = models.CharField(max_length=255, db_index=True) sort_name = models.CharField(max_length=255, db_index=True) # The "format" field is a legacy field that is being split into # color, dimensions, paper_stock, binding, and publishing_format format = models.CharField(max_length=255, default='') color = models.CharField(max_length=255, default='') dimensions = models.CharField(max_length=255, default='') paper_stock = models.CharField(max_length=255, default='') binding = models.CharField(max_length=255, default='') publishing_format = models.CharField(max_length=255, default='') publication_type = models.ForeignKey(SeriesPublicationType, on_delete=models.CASCADE, null=True, blank=True) notes = models.TextField() keywords = TaggableManager() year_began = models.IntegerField(db_index=True) year_ended = models.IntegerField(null=True) year_began_uncertain = models.BooleanField(default=False) year_ended_uncertain = models.BooleanField(default=False) is_current = models.BooleanField(default=False, db_index=True) publication_dates = models.CharField(max_length=255) first_issue = models.ForeignKey('Issue', on_delete=models.CASCADE, null=True, related_name='first_issue_series_set') last_issue = models.ForeignKey('Issue', on_delete=models.CASCADE, null=True, related_name='last_issue_series_set') issue_count = models.IntegerField(default=0) # Fields for tracking relationships between series. tracking_notes = models.TextField() awards = GenericRelation(ReceivedAward) # Fields for handling the presence of certain issue fields has_barcode = models.BooleanField(default=False) has_indicia_frequency = models.BooleanField(default=False) has_indicia_printer = models.BooleanField(default=False) has_isbn = models.BooleanField(default=False) has_issue_title = models.BooleanField(default=False) has_volume = models.BooleanField(default=False) has_rating = models.BooleanField(default=False) has_about_comics = models.BooleanField(default=False) has_publisher_code_number = models.BooleanField(default=False) is_comics_publication = models.BooleanField(default=False) is_singleton = models.BooleanField(default=False) # Fields related to cover image galleries. has_gallery = models.BooleanField(default=False, db_index=True) # Country and Language info. country = models.ForeignKey(Country, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) # Fields related to the publishers table. publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) def has_tracking(self): return self.tracking_notes or self.has_series_bonds() def has_series_bonds(self): return self.to_series_bond.exists() or self.from_series_bond.exists() def series_relative_bonds(self, **filter_args): """ Returns an unsorted list (not queryset!) of SeriesRelativeBond objects. SeriesRelativeBonds are not database objects, but can be sorted uniformly and provide access to the underlying SeriesBond. Does *not* automatically call has_series_bonds. """ bonds = [ SeriesRelativeBond(self, b) for b in self.to_series_bond.filter(**filter_args) ] bonds.extend([ SeriesRelativeBond(self, b) for b in self.from_series_bond.filter(**filter_args) ]) return bonds def has_dependents(self): # use active_issues() rather than issue_count to include variants. # TODO allow deletes of singletons with the issues, including # all variants ? # return ((not self.is_singleton and self.active_issues().exists()) or return (self.active_issues().exists() or self.issue_revisions.active_set().exists() or self.has_series_bonds()) def active_issues(self): return self.issue_set.exclude(deleted=True) def active_base_issues(self): """ All base issues, plus variants whose base is not in this series. For the purpose of ensuring that each logical issue has a representative in a list, logical issues that do not have a base issue in this series need to be represented by a variant. """ # TODO: What happens if there are two variants in this series # of the same logical issue that has its base in a # different series? return self.active_issues().exclude(variant_of__series=self) def active_base_issues_variant_count(self): issues = self.active_base_issues() issues = issues.annotate(variant_count=Count( Case(When(variant_set__deleted=False, then=1)))) return issues def active_non_base_variants(self): """ All non-base variants, including those with a base in another series. We want to be able to count all variant records related to this series, so we leave in the variants with bases in other series, as they can be further filtered out in cases where they are not desirable. """ return self.active_issues().exclude(variant_of=None) def active_indexed_issues(self): return self.active_issues().exclude(is_indexed=INDEXED['skeleton']) def set_first_last_issues(self): issues = self.active_issues().order_by('sort_code') if issues.count() == 0: self.first_issue = None self.last_issue = None else: self.first_issue = issues[0] self.last_issue = issues[len(issues) - 1] self.save() _update_stats = True def active_awards(self): return self.awards.exclude(deleted=True) def stat_counts(self): """ Returns all count values relevant to this series. Includes a count for the series itself. Non-comics publications do not return series and issue counts as they do not contribute those types of statistics. Story and cover statistics are tracked for all publications. """ if self.deleted: return {} counts = { 'covers': self.scan_count, 'stories': Story.objects.filter(issue__series=self).exclude( deleted=True).count(), } if self.is_comics_publication: counts['series'] = 1 # Need to filter out variants of bases in other series, which # are considered "base issues" with respect to this series. counts['issues'] = self.active_base_issues() \ .filter(variant_of=None).count() counts['variant issues'] = self.active_non_base_variants().count() counts['issue indexes'] = self.active_indexed_issues().count() else: # Non comics publications do not count for global stats, but # for publisher series counts. But not for issue counts. # TODO correctly process this counts['publisher series'] = 1 return counts def update_cached_counts(self, deltas, negate=False): """ Updates the database fields that cache child object counts. Expects a deltas object in the form returned by stat_counts() methods, and also expected by CountStats.update_all_counts(). In the case of series, there is only one local count (for issues). Note that we use 'series issues' rather than 'issues' for this count, because the series issue count tracks all non-variant issues, while all other issue counts ignore issues that are part of series that are not comics publications. """ if negate: deltas = deltas.copy() for k, v in deltas.items(): deltas[k] = -v # Don't apply F() if delta is 0, because we don't want # a lazy evaluation F-object result in a count field # if we don't absolutely need it. if deltas.get('series issues', 0): self.issue_count = F('issue_count') + deltas['series issues'] def ordered_brands(self): """ Provide information on publisher's brands in the order they first appear within the series. Returned as a list so that the UI can check the length of the list and the contents with only one DB call. """ return list( Brand.objects.filter( issue__series=self, issue__deleted=False).annotate( first_by_brand=models.Min('issue__sort_code'), used_issue_count=models.Count('issue')).order_by( 'first_by_brand')) def brand_info_counts(self): """ Simple method for the UI to use, as the UI can't pass parameters. """ # There really should be a way to do this in one annotate clause, but I # can't figure it out and the ORM may just not do it. The SQL would be: # SELECT (brand_id IS NULL AND no_brand = 0) AS unknown, COUNT(*) # FROM gcd_issue WHERE series_id=x GROUP BY unknown; # replacing x with the series id of course. return { 'no_brand': self.active_issues().filter(no_brand=True).count(), 'unknown': self.active_issues().filter(no_brand=False, brand__isnull=True).count(), } def ordered_indicia_publishers(self): """ Provide information on indicia publishers in the order they first appear within the series. Returned as a list so that the UI can check the length of the list and the contents with only one DB call. """ return list( IndiciaPublisher.objects.filter( issue__series=self, issue__deleted=False).annotate( first_by_ind_pub=models.Min('issue__sort_code'), used_issue_count=models.Count('issue')).order_by( 'first_by_ind_pub')) def indicia_publisher_info_counts(self): """ Simple method for the UI to use. Called _counts (plural) for symmetry with brand_info_counts which actually does return two counts. """ return { 'unknown': self.active_issues().filter( indicia_publisher__isnull=True).count(), } def get_ongoing_reservation(self): """ TODO: Rethink usage of 1-1 relation. """ try: return self.ongoing_reservation except models.ObjectDoesNotExist: return None def get_absolute_url(self): if self.id: return urlresolvers.reverse('show_series', kwargs={'series_id': self.id}) else: return '' def marked_scans_count(self): return Cover.objects.filter(issue__series=self, marked=True).count() @cached_property def scan_count(self): return Cover.objects.filter(issue__series=self, deleted=False).count() def issues_without_covers(self): issues = Issue.objects.filter(series=self).exclude(deleted=True) return issues.exclude(cover__isnull=False, cover__deleted=False)\ .distinct() @cached_property def scan_needed_count(self): return self.issues_without_covers().count() + self.marked_scans_count() @cached_property def issue_indexed_count(self): return self.active_base_issues()\ .exclude(is_indexed=INDEXED['skeleton']).count() @cached_property def issues_to_migrate(self): stories = Story.objects.exclude(Q(script='') | Q(script__startswith='?'), Q(pencils='') | Q(pencils__startswith='?'), Q(inks='') | Q(inks__startswith='?'), Q(colors='') | Q(colors__startswith='?'), feature='') \ .filter(issue__series__id=self.id) issues = self.active_issues().filter( id__in=set(stories.values_list('issue', flat=True))) return issues def _date_uncertain(self, flag): return ' ?' if flag else '' def display_publication_dates(self): if not self.issue_count: return '%s%s' % (str(self.year_began), self._date_uncertain(self.year_began_uncertain)) elif self.issue_count == 1: if self.first_issue.publication_date: return self.first_issue.publication_date else: return '%s%s' % (str(self.year_began), self._date_uncertain( self.year_began_uncertain)) else: if self.first_issue.publication_date: date = '%s - ' % self.first_issue.publication_date else: date = '%s%s - ' % (self.year_began, self._date_uncertain( self.year_began_uncertain)) if self.is_current: date += 'present' elif self.last_issue.publication_date: date += self.last_issue.publication_date elif self.year_ended: date += '%s%s' % (str(self.year_ended), self._date_uncertain( self.year_ended_uncertain)) else: date += '?' return date def search_result_name(self): if self.issue_count <= 1 and not self.is_current: date = '%s%s' % (str(self.year_began), self._date_uncertain(self.year_began_uncertain)) else: date = '%s%s - ' % (self.year_began, self._date_uncertain( self.year_began_uncertain)) if self.is_current: date += 'Present' elif self.year_ended: date += '%s%s' % (str(self.year_ended), self._date_uncertain( self.year_ended_uncertain)) else: date += '?' if self.is_singleton: issues = '' else: issues = '%d issue%s in' % (self.issue_count, pluralize(self.issue_count)) return '%s %s (%s) %s %s' % (self.name, self.short_pub_type(), self.publisher, issues, date) def short_pub_type(self): if self.publication_type: return '[' + self.publication_type.name[0] + ']' else: return '' def full_name(self): return '%s (%s, %s%s series)' % ( self.name, self.publisher, self.year_began, self._date_uncertain(self.year_began_uncertain)) def full_name_with_link(self, publisher=False): if publisher: name_link = '<a href="%s">%s</a> (<a href="%s">%s</a>,' \ ' %s%s series)' \ % (self.get_absolute_url(), esc(self.name), self.publisher.get_absolute_url(), self.publisher, self.year_began, self._date_uncertain(self.year_began_uncertain)) else: name_link = '<a href="%s">%s</a>' % (self.get_absolute_url(), esc(self.full_name())) return mark_safe(name_link) def cover_status_info(self): if not self.issue_count or not self.is_comics_publication: return "No Covers" else: gallery_url = urlresolvers.reverse("series_covers", kwargs={'series_id': self.id}) table_url = urlresolvers.reverse("series_scan_table", kwargs={'series_id': self.id}) if not self.scan_needed_count: return mark_safe('<a href="%s">Gallery</a>' % (gallery_url)) elif self.has_gallery: return mark_safe( '<a href="%s">Have %d</a> (<a href="%s">Need %d</a>)' % (gallery_url, self.scan_count, table_url, self.scan_needed_count)) else: return mark_safe('<a href="%s">Add</a>' % (table_url)) def __str__(self): return '%s (%s%s series)' % (self.name, self.year_began, self._date_uncertain( self.year_began_uncertain))
class GenRelReference(models.Model): references = GenericRelation(ReferencedByGenRel)
class Taxon(models.Model): """Despite its general name this currently represents a single species.""" objects = TaxonManager() scientific_name = models.CharField(max_length=100, unique=True) piles = models.ManyToManyField(Pile, through=Pile.species.through, related_name='+', blank=True) family = models.ForeignKey(Family, related_name='taxa') genus = models.ForeignKey(Genus, related_name='taxa') character_values = models.ManyToManyField(CharacterValue, through='TaxonCharacterValue') taxonomic_authority = models.CharField(max_length=100) images = GenericRelation(ContentImage) factoid = models.CharField(max_length=1000, blank=True) wetland_indicator_code = models.CharField(max_length=15, blank=True, null=True) north_american_native = models.NullBooleanField() north_american_introduced = models.NullBooleanField() description = models.CharField(max_length=500, blank=True) variety_notes = models.CharField(max_length=1000, blank=True) def natural_key(self): return (self.scientific_name, ) objects = TaxonManager() class Meta: verbose_name = 'taxon' verbose_name_plural = 'taxa' ordering = ['scientific_name'] def __unicode__(self): return u'%s id=%s' % (self.scientific_name, self.id) def slug(self): return self.scientific_name.lower().replace(' ', '-') def genus_name(self): """Determine the genus name without incurring a database query.""" return self.scientific_name.split(' ', 1)[0] @property def epithet(self): # convenience for forming URLs return self.scientific_name.split(' ', 1)[1].lower() def all_scientific_names(self): """Return a list of all the scientific names for this taxon, including the currently accepted scientific name and any synonyms. """ names = [synonym.scientific_name for synonym in self.synonyms.all()] names.append(self.scientific_name) return names def get_state_distribution_labels(self): """For each state covered on the site, return a label indicating the presence or absence of the species, and, where applicable, any invasive status. """ states = [key.upper() for key in settings.STATE_NAMES.keys()] distributions = Distribution.objects.all_records_for_plant( self.scientific_name).filter(state__in=states).values_list( 'state', 'present') invasive_statuses = InvasiveStatus.objects.filter( taxon=self).values_list('region', 'invasive_in_region', 'prohibited_from_sale') invasive_dict = { state: (invasive, prohibited) for state, invasive, prohibited in invasive_statuses } mapping = { settings.STATE_NAMES[state.lower()]: 'absent' for state in states } for state, present in distributions: if present == True: state = state.lower() key = settings.STATE_NAMES[state] label = 'present' if state in invasive_dict.keys(): invasive, prohibited = invasive_dict[state] if invasive: label += ', invasive' if prohibited: label += ', prohibited' mapping[key] = label labels = OrderedDict(sorted(mapping.iteritems())) return labels def get_default_image(self): try: return self.images.get(rank=1, image_type__name='habit') except ObjectDoesNotExist: return None def get_habitats(self): return (self.character_values.filter( character__short_name='habitat').order_by('value_str')) def get_wetland_indicator_text(self): return WetlandIndicator.objects.get( code=self.wetland_indicator_code).friendly_description def partners(self): return PartnerSite.objects.filter(species=self) def partner_users(self): users = [] for site in self.partners(): users.extend(site.users.all()) return users def natural_key(self): return (self.scientific_name, )
class TestCaseRun(TCMSActionModel): objects = TestCaseRunManager() case_run_id = models.AutoField(primary_key=True) case_text_version = models.IntegerField() running_date = models.DateTimeField(null=True, blank=True) close_date = models.DateTimeField(null=True, blank=True) notes = models.TextField(null=True, blank=True) sortkey = models.IntegerField(null=True, blank=True) environment_id = models.IntegerField(default=0) assignee = models.ForeignKey('auth.User', blank=True, null=True, related_name='case_run_assignee', on_delete=models.SET_NULL) tested_by = models.ForeignKey('auth.User', blank=True, null=True, related_name='case_run_tester', on_delete=models.SET_NULL) run = models.ForeignKey(TestRun, related_name='case_run', on_delete=models.CASCADE) case = models.ForeignKey('testcases.TestCase', related_name='case_run', on_delete=models.CASCADE) case_run_status = models.ForeignKey(TestCaseRunStatus, related_name='case_runs', on_delete=models.CASCADE) build = models.ForeignKey('management.TestBuild', on_delete=models.CASCADE) links = GenericRelation(LinkReference, object_id_field='object_pk') comments = GenericRelation(Comment, object_id_field='object_pk') class Meta: db_table = 'test_case_runs' unique_together = ('case', 'run', 'case_text_version') def __str__(self): return f'{self.pk}: {self.case_id}' @classmethod def to_xmlrpc(cls, query={}): from tcms.xmlrpc.serializer import TestCaseRunXMLRPCSerializer from tcms.xmlrpc.utils import distinct_filter qs = distinct_filter(TestCaseRun, query).order_by('pk') s = TestCaseRunXMLRPCSerializer(model_class=cls, queryset=qs) return s.serialize_queryset() @classmethod def mail_scene(cls, objects, field=None, value=None, ctype=None, object_pk=None): tr = objects[0].run # scence_templates format: # template, subject, context tcrs = objects.select_related() scence_templates = { 'assignee': { 'template_name': 'mail/change_case_run_assignee.txt', 'subject': 'Assignee of run %s has been changed' % tr.run_id, 'recipients': tr.get_notify_addrs(), 'context': { 'test_run': tr, 'test_case_runs': tcrs }, } } return scence_templates.get(field) def add_issue(self, issue_key, issue_tracker, summary=None, description=None, link_external_tracker=False): """Add an issue to this case run Every argument has same meaning of argument of :meth:`TestCase.add_issue`. :param str issue_key: issue key to add. :param issue_tracker: issue tracker the issue key should belong to. :type issue_tracker: :class:`IssueTracker` :param str summary: issue's summary. :param str description: issue's description. :param bool link_external_tracker: whether to add case to issue's external tracker in remote issue tracker. :return: the newly added issue. :rtype: :class:`Issue` """ return self.case.add_issue( issue_key=issue_key, issue_tracker=issue_tracker, summary=summary, description=description, case_run=self, link_external_tracker=link_external_tracker, ) def remove_issue(self, issue_key): """Remove issue from this case run :param str issue_key: issue key to remove. """ self.case.remove_issue(issue_key, case_run=self) def is_finished(self): return self.case_run_status.is_finished() def get_issues(self): """Get issues added to this case run :return: a queryset of the issues. """ return Issue.objects.filter(case_run=self) def get_issues_count(self): """Return the number of issues added to this case run :return: the number of issues. :rtype: int """ return self.get_issues().values('pk').count() def get_text_versions(self): return TestCaseText.objects.filter(case__pk=self.case.pk).values_list( 'case_text_version', flat=True) def get_text_with_version(self, case_text_version=None): if case_text_version: try: return TestCaseText.objects.get( case__case_id=self.case_id, case_text_version=case_text_version) except TestCaseText.DoesNotExist: return NoneText try: return TestCaseText.objects.get( case__case_id=self.case_id, case_text_version=self.case_text_version) except TestCaseText.DoesNotExist: return NoneText def get_previous_or_next(self): ids = list(self.run.case_run.values_list('case_run_id', flat=True)) current_idx = ids.index(self.case_run_id) prev = TestCaseRun.objects.get(case_run_id=ids[current_idx - 1]) try: next = TestCaseRun.objects.get(case_run_id=ids[current_idx + 1]) except IndexError: next = TestCaseRun.objects.get(case_run_id=ids[0]) return (prev, next) def latest_text(self): try: return TestCaseText.objects.filter( case__case_id=self.case_id).order_by('-case_text_version')[0] except IndexError: return NoneText
class SWATModelInstanceMetaData(ModelInstanceMetaData): _model_objective = GenericRelation(ModelObjective) _simulation_type = GenericRelation(SimulationType) _model_method = GenericRelation(ModelMethod) _model_parameter = GenericRelation(ModelParameter) _model_input = GenericRelation(ModelInput) @property def resource(self): return SWATModelInstanceResource.objects.filter( object_id=self.id).first() @property def model_objective(self): return self._model_objective.all().first() @property def simulation_type(self): return self._simulation_type.all().first() @property def model_method(self): return self._model_method.all().first() @property def model_parameter(self): return self._model_parameter.all().first() @property def model_input(self): return self._model_input.all().first() @classmethod def get_supported_element_names(cls): # get the names of all core metadata elements elements = super(SWATModelInstanceMetaData, cls).get_supported_element_names() # add the name of any additional element to the list elements.append('ModelObjective') elements.append('SimulationType') elements.append('ModelMethod') elements.append('ModelParameter') elements.append('ModelInput') return elements def has_all_required_elements(self): if not super(SWATModelInstanceMetaData, self).has_all_required_elements(): return False if not self.model_objective: return False return True def get_required_missing_elements(self): missing_required_elements = \ super(SWATModelInstanceMetaData, self).get_required_missing_elements() if not self.model_objective: missing_required_elements.append('ModelObjective') return missing_required_elements def update(self, metadata): # overriding the base class update method for bulk update of metadata super(SWATModelInstanceMetaData, self).update(metadata) attribute_mappings = { 'modelobjective': 'model_objective', 'simulationtype': 'simulation_type', 'modelmethod': 'model_method', 'modelparameter': 'model_parameter', 'modelinput': 'model_input', 'modeloutput': 'model_output', 'executedby': 'executed_by' } with transaction.atomic(): # update/create non-repeatable element for element_name in attribute_mappings.keys(): element_property_name = attribute_mappings[element_name] self.update_non_repeatable_element(element_name, metadata, element_property_name) def get_xml(self, pretty_print=True, include_format_elements=True): # get the xml string representation of the core metadata elements xml_string = super(SWATModelInstanceMetaData, self).get_xml(pretty_print=pretty_print) # create an etree xml object RDF_ROOT = etree.fromstring(xml_string) # get root 'Description' element that contains all other elements container = RDF_ROOT.find('rdf:Description', namespaces=self.NAMESPACES) if self.model_objective: hsterms_model_objective = etree.SubElement( container, '{%s}modelObjective' % self.NAMESPACES['hsterms']) if self.model_objective.other_objectives: hsterms_model_objective.text = self.model_objective.get_swat_model_objectives() + \ ', ' + self.model_objective.other_objectives else: hsterms_model_objective.text = self.model_objective.get_swat_model_objectives( ) if self.simulation_type: if self.simulation_type.simulation_type_name: hsterms_simulation_type = etree.SubElement( container, '{%s}simulationType' % self.NAMESPACES['hsterms']) hsterms_simulation_type.text = self.simulation_type.simulation_type_name if self.model_method: modelMethodFields = [ 'runoffCalculationMethod', 'flowRoutingMethod', 'petEstimationMethod' ] self.add_metadata_element_to_xml(container, self.model_method, modelMethodFields) if self.model_parameter: hsterms_swat_model_parameters = etree.SubElement( container, '{%s}modelParameter' % self.NAMESPACES['hsterms']) if self.model_parameter.other_parameters: hsterms_swat_model_parameters.text = \ self.model_parameter.get_swat_model_parameters() + ', ' + \ self.model_parameter.other_parameters else: hsterms_swat_model_parameters.text = \ self.model_parameter.get_swat_model_parameters() if self.model_input: modelInputFields = [ 'warmupPeriodType', 'warmupPeriodValue', 'rainfallTimeStepType', 'rainfallTimeStepValue', 'routingTimeStepType', 'routingTimeStepValue', 'simulationTimeStepType', 'simulationTimeStepValue', 'watershedArea', 'numberOfSubbasins', 'numberOfHRUs', 'demResolution', 'demSourceName', 'demSourceURL', 'landUseDataSourceName', 'landUseDataSourceURL', 'soilDataSourceName', 'soilDataSourceURL' ] self.add_metadata_element_to_xml(container, self.model_input, modelInputFields) return etree.tostring(RDF_ROOT, pretty_print=pretty_print) def delete_all_elements(self): super(SWATModelInstanceMetaData, self).delete_all_elements() self._model_objective.all().delete() self._simulation_type.all().delete() self._model_method.all().delete() self._model_parameter.all().delete() self._model_input.all().delete()
class OccurrenceNaturalArea(Occurrence): #details = models.OneToOneField(NaturalAreaDetails, on_delete=models.CASCADE, null=True) element = models.ForeignKey(ElementNaturalAreas, on_delete=models.CASCADE, blank=True, null=True) photographs = GenericRelation(Photograph, object_id_field='occurrence_fk') location = models.OneToOneField(NaturalAreaLocation, on_delete=models.CASCADE, null=True)
class B(models.Model): a = GenericRelation(A) class Meta: ordering = ('id',)
class Content(models.Model): nodes = GenericRelation(Node) related_obj = models.ForeignKey('Related', models.CASCADE)
class Survey(Model): """ read_only: Keep original data(read_only=True). Modify data(read_only=False). new field second and non_second table 1.4 """ farmer_id = CharField(max_length=12, verbose_name=_("Farmer Id")) farmer_name = CharField(null=True, blank=True, max_length=10, verbose_name=_("Name")) total_pages = IntegerField(verbose_name=_("Total Pages")) page = IntegerField(verbose_name=_("Page")) origin_class = IntegerField(null=True, blank=True, verbose_name=_("Origin Class")) second = BooleanField(default=False, verbose_name=_("Second")) non_second = BooleanField(default=False, verbose_name=_("Non Second")) hire = BooleanField(default=False, verbose_name=_("Hire")) non_hire = BooleanField(default=False, verbose_name=_("Non Hire")) lacks = ManyToManyField("surveys19.Lack", blank=True, related_name="surveys", verbose_name=_("Lack")) management_types = ManyToManyField( "surveys19.ManagementType", blank=True, related_name="surveys", verbose_name=_("Management Types"), ) note = TextField(null=True, blank=True, verbose_name=_("Note")) readonly = BooleanField(default=True, verbose_name=_("Read Only")) investigator = CharField(null=True, blank=True, max_length=10, verbose_name=_("Investigator")) reviewer = CharField(null=True, blank=True, max_length=10, verbose_name=_("Reviewer")) date = DateField(null=True, blank=True, verbose_name=_("Investigation Date")) distance = IntegerField(null=True, blank=True, verbose_name=_("Investigation Distance(km)")) period = IntegerField(null=True, blank=True, verbose_name=_("Investigation Period")) update_time = DateTimeField( auto_now=True, auto_now_add=False, null=True, blank=True, verbose_name=_("Updated"), ) review_logs = GenericRelation(ReviewLog, related_query_name="surveys19") class Meta: verbose_name = _("Survey") verbose_name_plural = _("Survey") def __str__(self): return self.farmer_id
class Company(models.Model): temp_model = ce_temp_model.TempCompany trade_district = models.ForeignKey(ce_models.TradeDistrict, on_delete=True) name = models.CharField(max_length=20) cash = models.DecimalField(decimal_places=2, max_digits=20, default=0) trash = GenericRelation(ce_models.Trash) profession_type_provided = models.CharField(default="", max_length=1) elementary_employee_needed = models.PositiveIntegerField(default=5) college_employee_needed = models.PositiveIntegerField(default=0) phd_employee_needed = models.PositiveIntegerField(default=0) employee = GenericRelation( to="citizen_engine.Citizen", object_id_field="workplace_object_id", content_type_field="workplace_content_type", ) def wage_payment(self, city, data): import decimal total_payment = [] for e in data.list_of_workplaces[self].all_employees: se = decimal.Decimal(data.citizens_in_city[e].salary_expectation) e.cash += se city.cash -= se total_payment.append(se) data.list_of_workplaces[self].workers_costs = sum(total_payment) def update_proficiency_of_profession_for_employees(self, employees): for employee in employees: employee.current_profession.update_proficiency(employee) def calculate_price_of_good(self, workers_costs, size_of_production): if workers_costs and size_of_production: return workers_costs / decimal.Decimal(size_of_production) return 0 def _get_productivity(self, data): productivity = [ self._get_energy_productivity(data), self._get_water_productivity(data), ] return sum(productivity) / len(productivity) def _get_energy_productivity(self, data): self_data_container = data.list_of_workplaces[self] if self_data_container.water_required: return self_data_container.energy / self_data_container.energy_required else: return 0 def _get_water_productivity(self, data): self_data_container = data.list_of_workplaces[self] if self_data_container.energy_required: return self_data_container.water / self_data_container.water_required else: return 0 def _get_quality(self, data): total = [] employee_categories = [ "elementary_employees", "college_employees", "phd_employees", ] employee_categories_needed = [ "elementary_employee_needed", "college_employee_needed", "phd_employee_needed", ] for e_cat, e_cat_needed in zip(employee_categories, employee_categories_needed): employees = self._get_employee_by_appendix(data.list_of_workplaces, data.citizens_in_city, e_cat) if employees: total.append( self._get_sum_edu_effectiveness(employees) / getattr(self, e_cat_needed) / 3) return sum(total) def _get_employee_by_appendix(self, workplaces, citizens, appendix): return ([citizens[e] for e in getattr(workplaces[self], appendix)] if getattr(workplaces[self], appendix) else []) def _get_avg_all_edu_effectiveness(self, citizen): return sum([edu.effectiveness for edu in citizen.educations]) / len( [edu.effectiveness for edu in citizen.educations]) def _get_sum_edu_effectiveness(self, employee_cat): return sum( [self._get_avg_all_edu_effectiveness(c) for c in employee_cat]) class Meta: abstract = True
class Circuit(CreatedUpdatedModel, CustomFieldModel): """ A communications circuit connects two points. Each Circuit belongs to a Provider; Providers may have multiple circuits. Each circuit is also assigned a CircuitType and a Site. A Circuit may be terminated to a specific device interface, but this is not required. Circuit port speed and commit rate are measured in Kbps. """ cid = models.CharField(max_length=50, verbose_name='Circuit ID') provider = models.ForeignKey('Provider', related_name='circuits', on_delete=models.PROTECT) type = models.ForeignKey('CircuitType', related_name='circuits', on_delete=models.PROTECT) tenant = models.ForeignKey(Tenant, related_name='circuits', blank=True, null=True, on_delete=models.PROTECT) install_date = models.DateField(blank=True, null=True, verbose_name='Date installed') commit_rate = models.PositiveIntegerField( blank=True, null=True, verbose_name='Commit rate (Kbps)') description = models.CharField(max_length=100, blank=True) comments = models.TextField(blank=True) custom_field_values = GenericRelation(CustomFieldValue, content_type_field='obj_type', object_id_field='obj_id') csv_headers = [ 'cid', 'provider', 'type', 'tenant', 'install_date', 'commit_rate', 'description' ] class Meta: ordering = ['provider', 'cid'] unique_together = ['provider', 'cid'] def __str__(self): return '{} {}'.format(self.provider, self.cid) def get_absolute_url(self): return reverse('circuits:circuit', args=[self.pk]) def to_csv(self): return csv_format([ self.cid, self.provider.name, self.type.name, self.tenant.name if self.tenant else None, self.install_date.isoformat() if self.install_date else None, self.commit_rate, self.description, ]) def _get_termination(self, side): for ct in self.terminations.all(): if ct.term_side == side: return ct return None @property def termination_a(self): return self._get_termination('A') @property def termination_z(self): return self._get_termination('Z')
class Cat(models.Model): name = models.CharField(max_length=12) owner = GenericRelation('Owner', related_query_name='owner')
class Application(TimeFieldsMixin, ConcurrentTransitionMixin): """Application for the jobs by Persons.""" related_name = 'applications' related_query_name = 'application' job = models.ForeignKey(Job, null=True, related_name=related_name, related_query_name=related_query_name) user = models.ForeignKey(User, related_name=related_name, related_query_name=related_query_name) state = FSMField(default=State.INTIATED, choices=State.CHOICES, db_index=True, protected=True, verbose_name='Application state.') reason_for_rejection = models.CharField( max_length=255, null=True, blank=True, help_text='Reason why the application was rejected.') images = GenericRelation(Image, related_query_name=related_query_name) videos = GenericRelation(Video, related_query_name=related_query_name) class Meta: """Meta options.""" unique_together = ('job', 'user') verbose_name = 'Application' verbose_name_plural = 'Applications' permissions = (("can_reject_candidate", "Can reject a candiate."), ) @transition(field=state, source=[State.INTIATED, State.PIPELINED, State.IGNORED], target=State.APPLIED) def applied(self): return @transition(field=state, source=State.INTIATED, target=State.PIPELINED) def pipelined(self): return @transition(field=state, source=State.INTIATED, target=State.IGNORED) def ignored(self): return @transition(field=state, source=[State.APPLIED, State.INTIATED], target=State.INVITED) def direct_invited(self): return @transition(field=state, source=State.SHORTLISTED, target=State.INVITED) def invited(self): return @transition(field=state, source=State.INVITED, target=State.INVITE_ACCEPTED) def invite_accepted(self): return @transition(field=state, source=State.INVITED, target=State.INVITE_REJECTED) def invite_rejected(self): return @transition(field=state, source=State.INVITE_REJECTED, target=State.REJECTED) def application_terminate(self): return @transition(field=state, source=State.INVITE_ACCEPTED, target=State.AUDITION_DONE) def audition_done(self): return @transition(field=state, source=[State.AUDITION_DONE, State.ONHOLD], target=State.ACCEPTED) def candidate_accepted(self): return @transition(field=state, source=[State.AUDITION_DONE, State.ONHOLD], target=State.REJECTED) def candidate_rejected(self): return @transition(field=state, source=State.AUDITION_DONE, target=State.ONHOLD) def candidate_on_hold(self): return @transition(field=state, source=[ State.IGNORED, State.PIPELINED, State.INVITED, State.APPLIED, State.SHORTLISTED, State.INVITE_ACCEPTED, State.INVITE_REJECTED, State.ONHOLD, State.AUDITION_DONE ], target=State.JOBCLOSED) def job_closed(self): return @transition(field=state, source=[ State.INTIATED, State.APPLIED, State.SHORTLISTED, State.INVITED, State.INVITE_ACCEPTED, State.AUDITION_DONE, State.ONHOLD ], target=State.REJECTED, permission='application.can_reject_candidate') def agent_rejected(self): return @transition(field=state, source=[State.INTIATED, State.APPLIED], target=State.SHORTLISTED, permission='application.can_reject_candidate') def shortlisted(self): return
class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(Tagged)
class Place(models.Model): name = models.CharField(max_length=100) links = GenericRelation(Link, related_query_name='places') link_proxy = GenericRelation(LinkProxy)
class Instance(ValidateModelMixin, models.Model): """ Instance: A web application or suite of web applications. An 'Instance' consists of an 'active' AppServer which is available at the instance's URL and handles all requests from users; the instance may also own some 'terminated' AppServers that are no longer used, and 'upcoming' AppServers that are used for testing before being designated as 'active'. In the future, we may add a scalable instance type, which owns a pool of active AppServers that all handle requests; currently at most one AppServer is active at any time. """ # Reverse accessor to get the 'InstanceReference' set. This is a 1:1 relation, so use the # 'ref' property instead of accessing this directly. The only time to use this directly is # in a query, e.g. to do .select_related('ref_set') ref_set = GenericRelation(InstanceReference, content_type_field='instance_type', object_id_field='instance_id') openstack_region = models.CharField( max_length=16, blank=False, default=default_setting('OPENSTACK_REGION'), ) tags = models.ManyToManyField( 'InstanceTag', blank=True, help_text='Custom tags associated with the instance.', ) class Meta: abstract = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.logger = ModelLoggerAdapter(logger, {'obj': self}) def __str__(self): return str(self.ref) @cached_property def ref(self): """ Get the InstanceReference for this Instance """ try: # This is a 1:1 relation, but django's ORM does not know that. # We use all() instead of get() or first() because all()[0] can be optimized better by django's ORM # (e.g. when using prefetch_related). return self.ref_set.all()[0] except IndexError: # The InstanceReference does not yet exist - create it: return InstanceReference(instance=self) def get_latest_deployment(self): """ Get the latest deployment for this instance """ if self.ref.deployment_set.exists(): return self.ref.deployment_set.latest() else: return None @property def name(self): """ Get this instance's name, which is stored in the InstanceReference """ return self.ref.name @property def instance_name(self): """ Get this instance's name, which is stored in the InstanceReference """ return self.ref.name @name.setter def name(self, new_name): """ Change the 'name' """ self.ref.name = new_name @property def created(self): """ Get this instance's created date, which is stored in the InstanceReference """ return self.ref.created @property def modified(self): """ Get this instance's modified date, which is stored in the InstanceReference """ return self.ref.modified @property def creator_username(self): """Get the username of the Ocim user who created the instance.""" if self.ref.creator: return self.ref.creator.user.username return None @property def owner_organization(self): """ Get the name of the Ocim organization who owns the instance. Relevant for sandboxes. """ if self.ref.owner: return self.ref.owner.name return None def save(self, *args, **kwargs): # pylint: disable=arguments-differ """ Save this Instance """ super().save(*args, **kwargs) # Ensure an InstanceReference exists, and update its 'modified' field: if self.ref.instance_id is None: self.ref.instance_id = self.pk # <- Fix needed when self.ref is accessed before the first self.save() self.ref.save() def refresh_from_db(self, using=None, fields=None): """ Reload from DB, or load related field. We override this to ensure InstanceReference is reloaded too. Otherwise, the name/created/modified properties could be out of date, even after Instance.refresh_from_db() is called. """ if fields is None: self.ref.refresh_from_db() super().refresh_from_db(using=using, fields=fields) @property def event_context(self): """ Context dictionary to include in events """ return { 'instance_id': self.ref.pk, 'instance_type': self.__class__.__name__ } def get_log_message_annotation(self): """ Get annotation for log message for this instance. """ return 'instance={} ({!s:.15})'.format(self.ref.pk, self.ref.name) @property def log_entries(self): """ Return the list of log entry instances for this Instance. Does NOT include log entries of associated AppServers or Servers (VMs) """ limit = settings.LOG_LIMIT instance_type = ContentType.objects.get_for_model(self) entries = LogEntry.objects.filter(content_type=instance_type, object_id=self.pk) # TODO: Filter out log entries for which the user doesn't have view rights return reversed(list(entries[:limit])) def archive(self, **kwargs): """ Mark this instance as archived. Subclasses should override this to shut down any active resources being used by this instance. """ self.ref.is_archived = True self.ref.save() def delete(self, **kwargs): # pylint: disable=arguments-differ """ Delete this Instance. This will delete the InstanceReference at the same time. """ if not kwargs.pop('ref_already_deleted', False): self.ref.delete(instance_already_deleted=True, **kwargs) super().delete(**kwargs)
class Person(models.Model): account = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) addresses = GenericRelation(Address)
class Comment(MPTTModel, TimestampModelMixin): objects = CommentManager() content_type = models.ForeignKey( ContentType, verbose_name="typ obsahu", related_name='content_type_set_for_%(class)s', on_delete=models.PROTECT) object_id = models.PositiveIntegerField(verbose_name="ID objektu") content_object = GenericForeignKey('content_type', 'object_id') parent = TreeForeignKey('self', verbose_name="nadradený", related_name='children', null=True, blank=True, on_delete=models.CASCADE) subject = models.CharField(verbose_name="predmet", max_length=100) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="používateľ", related_name='%(class)s_comments', blank=True, null=True, on_delete=models.SET_NULL) user_name = models.CharField(verbose_name="používateľské meno", max_length=50, blank=True) original_comment = RichTextOriginalField(verbose_name="obsah", filtered_field='filtered_comment', property_name='comment', max_length=COMMENT_MAX_LENGTH) filtered_comment = RichTextFilteredField() ip_address = models.GenericIPAddressField(verbose_name="IP adresa", blank=True, null=True) is_public = models.BooleanField(verbose_name="verejný", default=True) is_removed = models.BooleanField(verbose_name="odstránený", default=False) is_locked = models.BooleanField(verbose_name="uzamknutý", default=False) attachments = GenericRelation('attachment.Attachment') notes = GenericRelation('notes.Note') rating_statistics = GenericRelation('rating.Statistics') notification_events = GenericRelation('notifications.Event') content_fields = ('original_comment', ) def get_or_create_root_header(self): try: header = RootHeader.objects.get(content_type=self.content_type, object_id=self.object_id) except RootHeader.DoesNotExist: header = RootHeader.objects.get_or_create( content_type=self.content_type, object_id=self.object_id, defaults={ 'pub_date': self.created, 'last_comment': self.created, })[0] return header def get_absolute_url(self): return '%s#link_%d' % (reverse( 'comments:comments', args=(self.get_or_create_root_header().pk, ), kwargs={}), self.id) def get_single_comment_url(self): return reverse('comments:comment-single', args=(self.pk, )) def get_tags(self): tags = [] if getattr(self, 'is_new', False): tags.append('new') if not self.is_public: tags.append('private') if self.is_removed: tags.append('deleted') if tags: return ' ' + ' '.join(tags) else: return '' def _get_name(self): return self.user_name name = property(_get_name) def save(self, *args, **kwargs): if not self.user_name and self.user: self.user_name = force_str(self.user) return super().save(*args, **kwargs) def __str__(self): return self.subject class Meta: ordering = ('tree_id', 'lft') index_together = (( 'object_id', 'content_type', ), ) verbose_name = "komentár" verbose_name_plural = "komentáre"
class OddRelation1(models.Model): name = models.CharField(max_length=100) clinks = GenericRelation(CharLink)
class Person(models.Model): name = CharField(u'Имя', max_length=255) phone_number = GenericRelation('Phonenumber') class Meta: abstract = True
class OddRelation2(models.Model): name = models.CharField(max_length=100) tlinks = GenericRelation(TextLink)
class Form(TendenciBaseModel): """ A user-built form. """ FIRST = 1 MIDDLE = 2 LAST = 3 FIELD_POSITION_CHOICES = ( (FIRST, _("First")), (MIDDLE, _("Middle")), (LAST, _("Last")), ) INTRO_DEFAULT_NAME = _("Intro") FIELDS_DEFAULT_NAME = _("Fields") PRICING_DEFAULT_NAME = _("Pricings") title = models.CharField(_("Title"), max_length=100) slug = models.SlugField(max_length=100, unique=True) intro = models.TextField(_("Intro"), max_length=2000, blank=True) response = models.TextField(_("Confirmation Text"), max_length=2000, blank=True) email_text = models.TextField( _("Email Text to Submitter"), default='', blank=True, help_text= _("If Send email is checked, this is the text that will be sent in an email to the person submitting the form." ), max_length=2000) subject_template = models.CharField( _("Template for email subject "), help_text=_("""Options include [title] for form title, and name of form fields inside brackets [ ]. E.x. [first name] or [email address]"""), default="[title] - [first name] [last name] - [phone]", max_length=200, blank=True, null=True) send_email = models.BooleanField( _("Send email"), default=False, help_text=_( "If checked, the person submitting the form will be sent an email." )) email_from = models.EmailField( _("Reply-To address"), blank=True, help_text=_("The address the replies to the email will be sent to")) email_copies = models.CharField( _("Send copies to"), blank=True, help_text=_("One or more email addresses, separated by commas"), max_length=2000) completion_url = models.CharField( _("Completion URL"), max_length=1000, blank=True, null=True, help_text= _("Redirect to this page after form completion. Absolute URLS should begin with http. Relative URLs should begin with a forward slash (/)." )) template = models.CharField(_('Template'), max_length=50, blank=True) group = models.ForeignKey(Group, null=True, default=get_default_group, on_delete=models.SET_NULL) # payments custom_payment = models.BooleanField( _("Is Custom Payment"), default=False, help_text= _("If checked, please add pricing options below. Leave the price blank if users can enter their own amount." )) recurring_payment = models.BooleanField( _("Is Recurring Payment"), default=False, help_text= _("If checked, please add pricing options below. Leave the price blank if users can enter their own amount. Please also add an email field as a required field with type 'email'" )) payment_methods = models.ManyToManyField("payments.PaymentMethod", blank=True) perms = GenericRelation(ObjectPermission, object_id_field="object_id", content_type_field="content_type") # positions for displaying the fields intro_position = models.IntegerField(_("Intro Position"), choices=FIELD_POSITION_CHOICES, default=FIRST) fields_position = models.IntegerField(_("Fields Position"), choices=FIELD_POSITION_CHOICES, default=MIDDLE) pricing_position = models.IntegerField(_("Pricing Position"), choices=FIELD_POSITION_CHOICES, default=LAST) # variable name of form main sections intro_name = models.CharField(_("Intro Name"), max_length=50, default=INTRO_DEFAULT_NAME, blank=True) fields_name = models.CharField(_("Fields Name"), max_length=50, default=FIELDS_DEFAULT_NAME, blank=True) pricing_name = models.CharField(_("Pricing Name"), max_length=50, default=PRICING_DEFAULT_NAME, blank=True) objects = FormManager() class Meta: verbose_name = _("Form") verbose_name_plural = _("Forms") permissions = (("view_form", _("Can view form")), ) app_label = 'forms' def __unicode__(self): return self.title def save(self, *args, **kwargs): # If this is the current contact form, update checklist if str(self.pk) == get_setting('site', 'global', 'contact_form'): checklist_update('update-contact') super(Form, self).save(*args, **kwargs) @models.permalink def get_absolute_url(self): return ("form_detail", (), {"slug": self.slug}) def get_payment_type(self): if self.recurring_payment and self.custom_payment: return _("Custom Recurring Payment") if self.recurring_payment: return _("Recurring Payment") if self.custom_payment: return _("Custom Payment") def admin_link_view(self): url = self.get_absolute_url() return "<a href='%s'>%s</a>" % (url, ugettext("View on site")) admin_link_view.allow_tags = True admin_link_view.short_description = "" def admin_link_export(self): url = reverse("admin:forms_form_export", args=(self.id, )) return "<a href='%s'>%s</a>" % (url, ugettext("Export entries")) admin_link_export.allow_tags = True admin_link_export.short_description = "" def has_files(self): for field in self.fields.all(): if field.field_type == 'FileField': return True return False
class Contact(models.Model): notes = GenericRelation(Note)
class Question(models.Model): """Model class to contain every question in the forum.""" OPEN = "O" CLOSED = "C" DRAFT = "D" STATUS = ( (OPEN, _("Open")), (CLOSED, _("Closed")), (DRAFT, _("Draft")), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True, blank=False) timestamp = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=80, null=True, blank=True) status = models.CharField(max_length=1, choices=STATUS, default=DRAFT) content = MarkdownxField() has_answer = models.BooleanField(default=False) total_votes = models.IntegerField(default=0) votes = GenericRelation(Vote) tags = TaggableManager() objects = QuestionQuerySet.as_manager() secret = models.BooleanField(default=False) class Meta: ordering = ["-timestamp"] verbose_name = _("Question") verbose_name_plural = _("Questions") def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(f"{self.title}-{self.id}", to_lower=True, max_length=80) super().save(*args, **kwargs) def __str__(self): return self.title @property def count_answers(self): return Answer.objects.filter(question=self).count() def count_votes(self): """Method to update the sum of the total votes. Uses this complex query to avoid race conditions at database level.""" dic = Counter(self.votes.values_list("value", flat=True)) Question.objects.filter(id=self.id).update(total_votes=dic[True] - dic[False]) self.refresh_from_db() def get_upvoters(self): """Returns a list containing the users who upvoted the instance.""" return [vote.user for vote in self.votes.filter(value=True)] def get_downvoters(self): """Returns a list containing the users who downvoted the instance.""" return [vote.user for vote in self.votes.filter(value=False)] def get_answers(self): return Answer.objects.filter(question=self) def get_accepted_answer(self): return Answer.objects.get(question=self, is_answer=True) def get_markdown(self): return markdownify(self.content)
class Company(models.Model): name = models.CharField(max_length=100) links = GenericRelation(Link)
class Bookmark(models.Model): name = models.CharField(max_length=60) tag = GenericRelation(FunkyTag, related_query_name='bookmark') def __str__(self): return self.name
class Object(dalmeUuid): concept = models.ForeignKey('Concept', db_index=True, on_delete=models.CASCADE) instances = GenericRelation('Entity_phrase') tags = GenericRelation('Tag')
class ComponentModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) component = GenericRelation(Component, related_query_name="component") def __str__(self): return self.name
class Post(models.Model): VUE = "VUE" DJANGO = "DJANGO" PYTHON = "PYTHON" OTHER = "OTHER" THEMES = ( (DJANGO, "Django"), (VUE, "Vue"), (PYTHON, "Python"), (OTHER, "Other"), ) label_img = ProcessedImageField( upload_to=path_label_img, default="label_img/images.jpeg", processors=[ResizeToFill(500, 150)], format="JPEG", options={"quality": 100}, blank=True, null=True, ) theme = models.CharField(choices=THEMES, max_length=150) headline = models.CharField(max_length=500) description = models.CharField(max_length=1500, blank=True, null=True) article = HTMLField("Article") author = models.ForeignKey(USER, on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) views = models.IntegerField(default=0) likesystem = GenericRelation( "LikeSystem", related_query_name="post" ) # like and dislike objects comments = GenericRelation( "Comment", related_query_name="post" ) # comments class Meta: ordering = ["-id"] verbose_name = "Пост" verbose_name_plural = "Посты" def __str__(self): return self.headline def get_tags(self): tags = Tag.objects.all().filter(post=self) return tags def get_absolute_url(self): from django.urls import reverse return reverse("post_detail", args=[str(self.id)]) def get_created(self): created = pendulum.instance(self.created) created = created.format("DD MMMM YYYY", locale="ru") return created def comment_count(self): comment = Comment.objects.filter( content_type=ContentType.objects.get_for_model(self), object_id=self.id, ) return comment.count()