class EntrySearchVector(models.Model): """ A special class storing search vector for looking up entries. """ entry = models.OneToOneField(Entry, on_delete=models.CASCADE) text_vector = pg_search.SearchVectorField() speaker_vector = pg_search.SearchVectorField() class Meta: indexes = [ GinIndex(fields=['text_vector']), GinIndex(fields=['speaker_vector']) ] def update(self): lines = self.entry.lines.all() text_vector = pg_search.SearchVector(models.Value( strip_tags(self.entry.note), output_field=models.TextField()), weight='C', config='english') for tag in self.entry.tags.all(): text_vector += pg_search.SearchVector(models.Value( tag.name, output_field=models.TextField()), weight='A', config='english') for tag in self.entry.event.tags.all(): text_vector += pg_search.SearchVector(models.Value( tag.name, output_field=models.TextField()), weight='C', config='english') if lines.exists(): speaker_vectors = [] for line in lines: text_vector += pg_search.SearchVector(models.Value( strip_tags(line.text), output_field=models.TextField()), weight='B', config='english') speaker_vectors.append( pg_search.SearchVector(models.Value( strip_tags(line.speaker), output_field=models.TextField()), weight='A', config='english')) text_vector += pg_search.SearchVector(models.Value( strip_tags(line.speaker), output_field=models.TextField()), weight='D', config='english') speaker_vector = speaker_vectors[0] for sv in speaker_vectors[1:]: speaker_vector += sv self.speaker_vector = speaker_vector self.text_vector = text_vector self.save()
class PgQuestionSearch(models.Model): question = models.OneToOneField(Question, related_name='pg_question', on_delete=models.CASCADE) search_vector_title = pg_search.SearchVectorField(null=True) search_vector_text = pg_search.SearchVectorField(null=True) objects = PgSearchQuestionManager() class Meta: required_db_vendor = 'postgresql' indexes = [ GinIndex(fields=['search_vector_title', 'search_vector_text']) ]
class Berkas(MetaAtribut): nama_berkas = models.CharField("Nama Berkas", max_length=100, blank=True, null=True, db_index=True) berkas = FileField(upload_to=path_and_rename, max_length=255) no_berkas = models.CharField( "Nomor Berkas", max_length=30, blank=True, null=True, help_text="Masukkan Nomor Surat / Berkas jika ada.", db_index=True) keterangan = models.CharField("Keterangan", blank=True, null=True, max_length=255) sv = pg_search.SearchVectorField(null=True, blank=True) def get_file_url(self): if self.berkas: return settings.MEDIA_URL + str(self.berkas) return "#" def __unicode__(self): return str(self.nama_berkas) class Meta: indexes = [GinIndex(fields=['sv'])] verbose_name = 'Berkas' verbose_name_plural = 'Berkas'
class Channel(models.Model): """ An individual channel in the media platform. """ #: Object manager. See :py:class:`~.ChannelManager`. The objects returned by this manager do #: not include deleted objects. See :py:attr:\~.objects_including_deleted`. objects = ChannelManager() #: Object manager whose objects include the deleted items. This has been separated out into a #: separate manager to avoid inadvertently including deleted objects in a query objects_including_deleted = ChannelManager(include_deleted=True) #: Primary key id = models.CharField(max_length=_TOKEN_LENGTH, primary_key=True, default=_make_token, editable=False) #: Channel title title = models.TextField(help_text='Title of the channel', blank=False) #: Channel description description = models.TextField(help_text='Description of the channel', blank=True, default='') #: Full text search vector field text_search_vector = pgsearch.SearchVectorField() #: Billing account associated with this channel. To avoid potential data loss, once a billing #: account is associated with a channel we use the PROTECT argument to on_delete to prevent #: deletion of the account until it has no channels. billing_account = models.ForeignKey( 'BillingAccount', null=False, help_text='Billing account for the channel', on_delete=models.PROTECT, related_name='channels') #: Creation time created_at = models.DateTimeField(auto_now_add=True) #: Last update time updated_at = models.DateTimeField(auto_now=True) #: Deletion time. If non-NULL, the channel has been "deleted" and should not usually be #: visible. deleted_at = models.DateTimeField(null=True, blank=True) def __str__(self): return '{} ("{}")'.format(self.id, self.title) class Meta: indexes = ( models.Index(fields=['created_at']), models.Index(fields=['updated_at']), models.Index(fields=['deleted_at']), pgindexes.GinIndex(fields=['text_search_vector']), )
class Negara(models.Model): nama_negara = models.CharField(max_length=40, verbose_name="Negara", db_index=True) keterangan = models.CharField(max_length=255, blank=True, null=True, verbose_name="Keterangan") code = models.CharField(max_length=10, blank=True, null=True, verbose_name="Kode Negara") lt = models.CharField(max_length=100, null=True, blank=True, verbose_name='Latitute') lg = models.CharField(max_length=100, null=True, blank=True, verbose_name='Longitute') sv = pg_search.SearchVectorField(null=True, blank=True) def __unicode__(self): return "%s" % (self.nama_negara, ) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['nama_negara'] verbose_name = "Negara" verbose_name_plural = "Negara"
class Migration(migrations.Migration): dependencies = [ ('ansible', '0003_add_tags_and_collectionversion_fields'), ] operations = [ migrations.RenameField( model_name='tag', old_name='_id', new_name='pulp_id', ), migrations.AddField( model_name='collectionversion', name='search_vector', field=psql_search.SearchVectorField(default=''), ), migrations.RunSQL( sql=POPULATE_COLLECTIONS_TS_VECTOR, reverse_sql=migrations.RunSQL.noop, ), migrations.RunSQL( sql=CREATE_COLLECTIONS_TS_VECTOR_TRIGGER, reverse_sql=DROP_COLLECTIONS_TS_VECTOR_TRIGGER, ) ]
class SearchFeature(DCFModel): objects: Manager["SearchFeature"] content_type = m.ForeignKey(ContentType, on_delete=m.CASCADE, null=True) object_id = m.UUIDField(null=True, db_index=True) content_object = GenericForeignKey("content_type", "object_id") text_feature = m.TextField() search_vector = s.SearchVectorField() class Meta: unique_together = index_together = ["object_id", "content_type"] indexes = [GinIndex(fields=["search_vector"])]
class JenisKelamin(models.Model): jenis_kelamin = models.CharField("Jenis Kelamin", max_length=100, db_index=True) keterangan = models.CharField("Keterangan", blank=True, null=True, max_length=255) sv = pg_search.SearchVectorField(null=True, blank=True) def __unicode__(self): return self.jenis_kelamin class Meta: indexes = [GinIndex(fields=['sv'])] verbose_name='Jenis Kelamin' verbose_name_plural='Jenis Kelamin'
class Agama(models.Model): agama = models.CharField("Agama", max_length=100, unique=True, db_index=True) keterangan = models.CharField("Keterangan", blank=True, null=True, max_length=255) sv = pg_search.SearchVectorField(null=True, blank=True) def __unicode__(self): return self.agama class Meta: indexes = [GinIndex(fields=['sv'])] verbose_name='Agama' verbose_name_plural='Agama'
class Opening(Entity): """Defines fields for recording job opening details. """ entry_hash = models.CharField('Title Hash', max_length=200, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) locations = models.ManyToManyField(Location, blank=True) role_title = models.CharField('Role Title', max_length=100) description = models.TextField() url = models.URLField('Job Url', max_length=200, unique=True) is_remote = models.NullBooleanField('Is Remote') part_time_permitted = models.NullBooleanField('Part-Time Permitted') has_401k = models.NullBooleanField('Has 401k') has_dentalins = models.NullBooleanField('Has Dental Insurance') has_healthins = models.NullBooleanField('Has Health Insurance') salary_range = pgmodels.IntegerRangeField('Salary Range', blank=True, null=True) date_active = models.DateField('Date Active', auto_now=False, auto_now_add=False) date_inactive = models.DateField( 'Date Inactive', auto_now=False, auto_now_add=False, blank=True, null=True ) date_created = models.DateTimeField('Date Created', auto_now=False, auto_now_add=True) tsdocument = search.SearchVectorField('Document') def is_match(self, data: dict): """Returns True if data matches opening details otherwise False. :param data: details to match against this opening instance. :type data: dict """ pattern = re.compile('date_*') exclude_list = ( 'id', 'company', 'locations', 'entry_hash', 'tsdocument' ) field_names = list(filter( lambda f: f not in exclude_list and not pattern.match(f), [f.name for f in self._meta.get_fields()] )) for field in field_names: if ( field in data['job'] and hasattr(self, field) and getattr(self, field) != data['job'][field] ): return False return True def __str__(self): """Returns string representation of the model. """ return f'{self.role_title} at {self.company.name}'
class JenisNomorIdentitas(models.Model): jenis_nomor_identitas = models.CharField(max_length=30, verbose_name='Jenis Nomor Identitas') keterangan = models.CharField(max_length=255, blank=True, null=True) sv = pg_search.SearchVectorField(null=True, blank=True) def __unicode__(self): return u'%s. %s' % (self.id, self.jenis_nomor_identitas) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['id'] verbose_name = 'Jenis Nomor Identitas' verbose_name_plural = 'Jenis Nomor Identitas'
class ArchivePage(models.Model): oldmgid = models.TextField() id = models.TextField(primary_key=True) download_link = models.TextField(blank=True, null=True) direct_link = models.TextField(blank=True, null=True) thumbnail_url = models.TextField(blank=True, null=True) publication_date = models.DateField(blank=True, null=True) page = models.IntegerField(blank=True, null=True) text = models.TextField(blank=True, null=True) tsv = search.SearchVectorField(null=True) class Meta: managed = True db_table = 'archive'
class Collection(mixins.TimestampsMixin, models.Model): """ A model representing an Ansible Content Collection. :var namespace: Reference to a collection nanespace. :var name: Collection name. :var deprecated: Indicates if a collection is deprecated. :var download_count: Number of collection downloads. :var comminity_score: Total community score. :var community_survey_count: Number of community surveys. :var tags: List of a last collection version tags. """ namespace = models.ForeignKey(Namespace, on_delete=models.PROTECT) name = models.CharField(max_length=64) deprecated = models.BooleanField(default=False) # Community and quality score download_count = models.IntegerField(default=0) community_score = models.FloatField(null=True) community_survey_count = models.IntegerField(default=0) # References latest_version = models.ForeignKey( 'CollectionVersion', on_delete=models.SET_NULL, related_name='+', null=True, ) tags = models.ManyToManyField('Tag') # Search indexes search_vector = psql_search.SearchVectorField(default='') class Meta: unique_together = ( 'namespace', 'name', ) indexes = [psql_indexes.GinIndex(fields=['search_vector'])] def __str__(self): return '{}.{}'.format(self.namespace.name, self.name) def inc_download_count(self): Collection.objects.filter(pk=self.pk).update( download_count=models.F('download_count') + 1)
class Entry(models.Model): """A blog entry with authors field.""" blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField(auto_now_add=True) mod_date = models.DateField(auto_now=True) authors = models.ManyToManyField(Author) n_comments = models.IntegerField(default=0) n_pingbacks = models.IntegerField(default=0) rating = models.IntegerField(default=5) search_vector = search.SearchVectorField(null=True) def __str__(self): """Return the string representation.""" return self.headline
class Kabupaten(models.Model): """docstring for Kabupaten""" provinsi = models.ForeignKey(Provinsi, on_delete=models.CASCADE, verbose_name="Provinsi", db_index=True) kode = models.CharField(verbose_name="Kode", max_length=6, blank=True, null=True, db_index=True) nama_kabupaten = models.CharField(max_length=40, verbose_name="Kabupaten / Kota") keterangan = models.CharField(max_length=255, blank=True, null=True, verbose_name="Keterangan") lt = models.CharField(max_length=100, null=True, blank=True, verbose_name='Latitute') lg = models.CharField(max_length=100, null=True, blank=True, verbose_name='Longitute') sv = pg_search.SearchVectorField(null=True, blank=True) def as_option(self): return "<option value='" + str(self.id) + "'>" + str( self.nama_kabupaten) + "</option>" def as_option_complete(self): return "<option value='" + str(self.id) + "'>" + str( self.nama_kabupaten) + ", " + str( self.provinsi.nama_provinsi) + " - " + str( self.provinsi.negara.nama_negara) + "</option>" def __unicode__(self): return "%s" % (self.nama_kabupaten, ) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['nama_kabupaten'] verbose_name = "Kabupaten / Kota" verbose_name_plural = "Kabupaten / Kota"
class Provinsi(models.Model): negara = models.ForeignKey(Negara, on_delete=models.CASCADE, verbose_name="Negara", db_index=True) kode = models.CharField(verbose_name="Kode", max_length=6, blank=True, null=True, db_index=True) nama_provinsi = models.CharField(max_length=40, verbose_name="Provinsi") keterangan = models.CharField(max_length=255, blank=True, null=True, verbose_name="Keterangan") lt = models.CharField(max_length=100, null=True, blank=True, verbose_name='Latitute') lg = models.CharField(max_length=100, null=True, blank=True, verbose_name='Longitute') sv = pg_search.SearchVectorField(null=True, blank=True) def as_json(self): return dict(id=self.id, nama_provinsi=self.nama_provinsi, negara=self.negara.nama_negara, keterangan=self.keterangan) def as_option(self): return "<option value='" + str(self.id) + "'>" + str( self.nama_provinsi) + "</option>" def __unicode__(self): return "%s" % (self.nama_provinsi, ) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['nama_provinsi'] verbose_name = "Provinsi" verbose_name_plural = "Provinsi"
class Kecamatan(models.Model): """docstring for Kecamatan""" kabupaten = models.ForeignKey(Kabupaten, on_delete=models.CASCADE, verbose_name="Kabupaten / Kota", db_index=True) kode = models.CharField(verbose_name="Kode", max_length=6, blank=True, null=True, db_index=True) nama_kecamatan = models.CharField(max_length=40, verbose_name="Kecamatan") keterangan = models.CharField(max_length=255, blank=True, null=True, verbose_name="Keterangan") lt = models.CharField(max_length=100, null=True, blank=True, verbose_name='Latitute') lg = models.CharField(max_length=100, null=True, blank=True, verbose_name='Longitute') sv = pg_search.SearchVectorField(null=True, blank=True) def as_json(self): return dict(id=self.id, nama_kecamatan=self.nama_kecamatan, keterangan=self.keterangan) def as_option(self): return "<option value='" + str(self.id) + "'>" + str( self.nama_kecamatan) + "</option>" def __unicode__(self): return "%s" % (self.nama_kecamatan, ) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['nama_kecamatan'] verbose_name = "Kecamatan" verbose_name_plural = "Kecamatan"
class Migration(migrations.Migration): dependencies = [ ('main', '0082_apb_content_type'), ] operations = [ migrations.AddField( model_name='content', name='search_vector', field=psql_search.SearchVectorField(default=''), preserve_default=False, ), migrations.AddIndex( model_name='content', index=psql_indexes.GinIndex(fields=['search_vector'], name='main_conten_search__47815a_gin'), ), migrations.RunSQL(sql=(SET_SEARCH_VECTOR, CREATE_SEARCH_VECTOR_UPDATE_TRIGGER), reverse_sql=DROP_SEARCH_VECTOR_UPDATE_TRIGGER), ]
class Account(AbstractBaseUser, PermissionsMixin, MetaAtribut): email = models.EmailField(unique=True, blank=True, null=True) username = models.CharField(max_length=40, unique=True, db_index=True) first_name = models.CharField("Nama Depan", max_length=100, null=True, blank=True, db_index=True) last_name = models.CharField("Nama Belakang", max_length=100, null=True, blank=True, db_index=True) tempat_lahir = models.CharField(max_length=30, verbose_name='Tempat Lahir', null=True, blank=True) tanggal_lahir = models.DateField(verbose_name='Tanggal Lahir', null=True, blank=True) telephone = models.CharField(verbose_name='Telepon', max_length=50, null=True, blank=True) id_divisi = models.CharField(verbose_name='ID Divisi', max_length=40, null=True, blank=True) divisi = models.CharField(verbose_name='Divisi', max_length=50, null=True, blank=True) id_jabatan = models.CharField(verbose_name='ID Jabatan', max_length=40, null=True, blank=True) jabatan = models.CharField(verbose_name='Jabatan', max_length=50, null=True, blank=True) status_pernikahan = models.CharField(verbose_name='Status Pernikahan', max_length=50, null=True, blank=True) jumlah_anak = models.CharField(verbose_name='Jumlah Anak', max_length=50, null=True, blank=True) agama = models.CharField(verbose_name='Agama', max_length=50, null=True, blank=True) golongan_darah = models.CharField(verbose_name='Golongan Darah', max_length=50, null=True, blank=True) id_provinsi = models.CharField(verbose_name="ID Provinsi", max_length=40, null=True, blank=True) provinsi = models.CharField(verbose_name="Provinsi", max_length=80, null=True, blank=True) id_kabupaten = models.CharField(verbose_name="ID Kabupaten", max_length=40, null=True, blank=True) kabupaten = models.CharField(verbose_name="Kabupaten", max_length=100, null=True, blank=True) id_kecamatan = models.CharField(verbose_name="ID Kecamatan", max_length=40, null=True, blank=True) kecamatan = models.CharField(verbose_name="Kecamatan", max_length=100, null=True, blank=True) id_desa = models.CharField(verbose_name="ID Desa", max_length=40, null=True, blank=True) desa = models.CharField(verbose_name="Desa", max_length=150, null=True, blank=True) alamat = models.CharField(verbose_name="Alamat", max_length=255, null=True, blank=True) lt = models.CharField(max_length=50, verbose_name='lt', blank=True, null=True) lg = models.CharField(max_length=50, verbose_name='lg', blank=True, null=True) foto = models.CharField(verbose_name="Foto", max_length=150, null=True, blank=True) sv = pg_search.SearchVectorField(null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [ 'email', ] def get_complete_location_dictionary(self): negara = '' provinsi = '' kabupaten = '' kecamatan = '' desa = '' negara_id = '' provinsi_id = '' kabupaten_id = '' kecamatan_id = '' desa_id = '' if self.desa: return self.desa.get_complete_location_dictionary() return dict(negara=negara, negara_id=negara_id, provinsi=provinsi, provinsi_id=provinsi_id, kabupaten=kabupaten, kabupaten_id=kabupaten_id, kecamatan=kecamatan, kecamatan_id=kecamatan_id, desa=desa, desa_id=desa_id) # @property def get_years_birthday(self): years = "-" if self.tanggal_lahir: rdelta = relativedelta(date.today(), self.tanggal_lahir) years = rdelta.years return years return years def get_month_birthday(self): months = "-" if self.tanggal_lahir: rdelta = relativedelta(date.today(), self.tanggal_lahir) months = rdelta.months return months return months def get_day_birthday(self): days = "-" if self.tanggal_lahir: rdelta = relativedelta(date.today(), self.tanggal_lahir) days = rdelta.days return days return days def is_staff(self): "Allow All Member to Login" # Simplest possible answer: All admins are staff return self.is_active def get_full_name(self): # The user is identified by their nama if self.first_name: return self.first_name + ' ' + self.last_name else: return '' def get_alamat(self): a = "-" if self.alamat: a = self.alamat if self.desa: a = a + " " + self.desa.alamat_lengkap() return a def __str__(self): return u'%s' % (self.email) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['id'] verbose_name = 'Akun' verbose_name_plural = 'Akun'
class CollectionVersion(Content): """ A content type representing a CollectionVersion. This model is primarily designed to adhere to the data format for Collection content. That spec is here: https://docs.ansible.com/ansible/devel/dev_guide/collections_galaxy_meta.html Fields: authors (psql_fields.ArrayField): A list of the CollectionVersion content's authors. contents (models.JSONField): A JSON field with data about the contents. dependencies (models.JSONField): A dict declaring Collections that this collection requires to be installed for it to be usable. description (models.TextField): A short summary description of the collection. docs_blob (models.JSONField): A JSON field holding the various documentation blobs in the collection. manifest (models.JSONField): A JSON field holding MANIFEST.json data. files (models.JSONField): A JSON field holding FILES.json data. documentation (models.CharField): The URL to any online docs. homepage (models.CharField): The URL to the homepage of the collection/project. issues (models.CharField): The URL to the collection issue tracker. license (psql_fields.ArrayField): A list of licenses for content inside of a collection. name (models.CharField): The name of the collection. namespace (models.CharField): The namespace of the collection. repository (models.CharField): The URL of the originating SCM repository. version (models.CharField): The version of the collection. requires_ansible (models.CharField): The version of Ansible required to use the collection. is_highest (models.BooleanField): Indicates that the version is the highest one in the collection. Relations: collection (models.ForeignKey): Reference to a collection model. tag (models.ManyToManyField): A symmetric reference to the Tag objects. """ TYPE = "collection_version" # Data Fields authors = psql_fields.ArrayField(models.CharField(max_length=64), default=list, editable=False) contents = models.JSONField(default=list, editable=False) dependencies = models.JSONField(default=dict, editable=False) description = models.TextField(default="", blank=True, editable=False) docs_blob = models.JSONField(default=dict, editable=False) manifest = models.JSONField(default=dict, editable=False) files = models.JSONField(default=dict, editable=False) documentation = models.CharField(default="", blank=True, max_length=2000, editable=False) homepage = models.CharField(default="", blank=True, max_length=2000, editable=False) issues = models.CharField(default="", blank=True, max_length=2000, editable=False) license = psql_fields.ArrayField(models.CharField(max_length=32), default=list, editable=False) name = models.CharField(max_length=64, editable=False) namespace = models.CharField(max_length=64, editable=False) repository = models.CharField(default="", blank=True, max_length=2000, editable=False) version = models.CharField(max_length=128, editable=False) requires_ansible = models.CharField(null=True, max_length=255) is_highest = models.BooleanField(editable=False, default=False) # Foreign Key Fields collection = models.ForeignKey(Collection, on_delete=models.PROTECT, related_name="versions", editable=False) tags = models.ManyToManyField(Tag, editable=False) # Search Fields search_vector = psql_search.SearchVectorField(default="") @property def relative_path(self): """ Return the relative path for the ContentArtifact. """ return "{namespace}-{name}-{version}.tar.gz".format( namespace=self.namespace, name=self.name, version=self.version) class Meta: default_related_name = "%(app_label)s_%(model_name)s" unique_together = ("namespace", "name", "version") constraints = [ UniqueConstraint( fields=("collection", "is_highest"), name="unique_is_highest", condition=Q(is_highest=True), ) ]
class Invoice(models.Model): INVOICE_TYPE_INVOICE = 'invoice' INVOICE_TYPE_PROFORMA = 'proforma' INVOICE_TYPE_CREDIT = 'credit' INVOICE_TYPE_DEBIT = 'debit' INVOICE_TYPES = ( (INVOICE_TYPE_INVOICE, _('Фактура')), (INVOICE_TYPE_PROFORMA, _('Проформа')), (INVOICE_TYPE_CREDIT, _('Кредит')), (INVOICE_TYPE_DEBIT, _('Дебит')), ) user = models.ForeignKey(User, on_delete=models.CASCADE) client_name = models.CharField(max_length=255, db_index=True, default='') client_city = models.CharField(max_length=255, default='') client_address = models.CharField(max_length=255, default='', db_index=True) client_mol = models.CharField(max_length=255, default='') client_eik = models.CharField(max_length=255, db_index=True) client_dds = models.CharField(max_length=255, null=True, blank=True) created_by = models.CharField(max_length=255, null=True) accepted_by = models.CharField(max_length=255, null=True) invoice_type = models.CharField(max_length=10, choices=INVOICE_TYPES, db_index=True, blank=False, default='invoice') number = models.PositiveIntegerField(db_index=True) ref_number = models.PositiveIntegerField(blank=True, null=True) released_at = models.DateField(blank=True, null=True) taxevent_at = models.DateField(blank=True, null=True) dds_percent = models.DecimalField( max_digits=10, decimal_places=2, default=0.0, blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(100)]) note = models.TextField(blank=True, default='') no_dds_reason = models.CharField(max_length=255, default='') currency = models.CharField(max_length=3, null=True) currency_rate = models.DecimalField(max_digits=10, decimal_places=6, null=True) payment_iban = models.CharField(max_length=255, null=True) payment_swift = models.CharField(max_length=255, null=True) payment_type = models.CharField(max_length=155, null=True) payment_bank = models.CharField(max_length=255, null=True) search_vector = pg_search.SearchVectorField(null=True) deleted = models.BooleanField(null=False, default=False) class Meta: ordering = ("-released_at", "-invoice_type", "-number") unique_together = ("user", "invoice_type", "number") indexes = [GinIndex(fields=['search_vector'])] def __str__(self): return self.client_name def __pre__(self): return self.client_name @property def is_last(self): return self.pk and (self.number == ( get_next_number(self.user, self.invoice_type) - 1)) @property def is_proforma(self): return self.invoice_type == self.INVOICE_TYPE_PROFORMA @property def gross(self): prices = [item.total for item in self.invoiceitem_set.all()] return sum(prices) @property def total(self): if self.dds_percent: return round( self.gross + (self.gross * float(self.dds_percent) / 100), 2) else: return round(self.gross, 2) def save(self, *args, **kwargs): if not self.number: self.number = get_next_number(self.user, self.invoice_type) super(Invoice, self).save(*args, **kwargs)
class Account(AbstractBaseUser,PermissionsMixin, MetaAtribut): email = models.EmailField(unique=True, blank=True, null=True) username = models.CharField(max_length=40, unique=True, db_index=True) first_name = models.CharField("Nama Depan", max_length=100, db_index=True) last_name = models.CharField("Nama Belakang", max_length=100, db_index=True) tempat_lahir = models.CharField(max_length=30, verbose_name='Tempat Lahir', null=True, blank=True) tanggal_lahir = models.DateField(verbose_name='Tanggal Lahir', null=True, blank=True) telephone = models.CharField(verbose_name='Telepon', max_length=50, null=True, blank=True) desa = models.ForeignKey(Desa, on_delete=models.CASCADE, verbose_name="Desa", null=True, blank=True) alamat = models.CharField(max_length=255) lt = models.CharField(max_length=50, verbose_name='lt', blank=True, null=True) lg = models.CharField(max_length=50, verbose_name='lg', blank=True, null=True) foto = ImageField(upload_to=path_and_rename, max_length=255, null=True, blank=True) sv = pg_search.SearchVectorField(null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] # 'first_name','last_name'] def get_complete_location_dictionary(self): negara = '' provinsi = '' kabupaten = '' kecamatan = '' desa = '' negara_id = '' provinsi_id = '' kabupaten_id = '' kecamatan_id= '' desa_id = '' if self.desa: return self.desa.get_complete_location_dictionary() return dict(negara=negara, negara_id=negara_id, provinsi=provinsi, provinsi_id=provinsi_id, kabupaten=kabupaten, kabupaten_id=kabupaten_id, kecamatan=kecamatan, kecamatan_id=kecamatan_id, desa=desa, desa_id=desa_id) # def is_pegawai(self): # if request.user.pegawai: # return True # else: # return False # @property def get_years_birthday(self): years = "-" if self.tanggal_lahir: rdelta = relativedelta(date.today(), self.tanggal_lahir) years = rdelta.years return years return years def get_month_birthday(self): months = "-" if self.tanggal_lahir: rdelta = relativedelta(date.today(), self.tanggal_lahir) months = rdelta.months return months return months def get_day_birthday(self): days = "-" if self.tanggal_lahir: rdelta = relativedelta(date.today(), self.tanggal_lahir) days = rdelta.days return days return days def is_staff(self): "Allow All Member to Login" # Simplest possible answer: All admins are staff return self.is_active # def get_short_name(self): # # The user is identified by their nama # return self.nama_lengkap def get_full_name(self): # The user is identified by their nama return self.first_name +' '+ self.last_name def get_alamat(self): a = "-" if self.alamat: a = self.alamat if self.desa: a = a+" "+self.desa.alamat_lengkap() return a def get_foto(self): if self.foto: return settings.MEDIA_URL+str(self.foto.url) return settings.STATIC_URL+"images/no-avatar.jpg" def get_nip_format(self): j = str(self.username) awal = j[:8] tengah = j[-10:] tengah_1 = tengah[:6] akhir = j[-4:] akhir_1 = akhir[:1] akhir_2 = akhir[-3:] gabung = awal +" "+tengah_1+" "+akhir_1+" "+akhir_2 return gabung def __str__(self): return u'%s' % (self.email) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['id'] verbose_name = 'Akun' verbose_name_plural = 'Akun'
class Account(AbstractBaseUser, PermissionsMixin, MetaAtribut): id = models.UUIDField(primary_key=True, default=uuid.uuid4) email = models.EmailField(unique=True, blank=True, null=True) username = models.CharField(max_length=40, unique=True, db_index=True) first_name = models.CharField("Nama Depan", max_length=100, null=True, blank=True, db_index=True) last_name = models.CharField("Nama Belakang", max_length=100, null=True, blank=True, db_index=True) birth_place = models.CharField(max_length=30, verbose_name='Tempat Lahir', null=True, blank=True) birth_date = models.DateField(verbose_name='Tanggal Lahir', null=True, blank=True) telephone = models.CharField(verbose_name='Telepon', max_length=50, null=True, blank=True) id_divisi = models.CharField(verbose_name='ID Divisi', max_length=40, null=True, blank=True) divisi = models.CharField(verbose_name='Divisi', max_length=64, null=True, blank=True) id_jabatan = models.CharField(verbose_name='ID Jabatan', max_length=40, null=True, blank=True) jabatan = models.CharField(verbose_name='Jabatan', max_length=64, null=True, blank=True) marital_status = models.CharField(verbose_name='Status Pernikahan', max_length=50, null=True, blank=True) number_children = models.CharField(verbose_name='Jumlah Anak', max_length=50, null=True, blank=True) religion = models.CharField(verbose_name='Agama', max_length=50, null=True, blank=True) blood_type = models.CharField(verbose_name='Golongan Darah', max_length=50, null=True, blank=True) gender = models.CharField(verbose_name='Jenis Kelamin', max_length=50, null=True, blank=True) id_province = models.CharField(verbose_name="ID Provinsi", max_length=40, null=True, blank=True) province = models.CharField(verbose_name="Provinsi", max_length=80, null=True, blank=True) id_districts = models.CharField(verbose_name="ID Kabupaten", max_length=40, null=True, blank=True) districts = models.CharField(verbose_name="Kabupaten", max_length=100, null=True, blank=True) id_sub_district = models.CharField(verbose_name="ID Kecamatan", max_length=40, null=True, blank=True) sub_district = models.CharField(verbose_name="Kecamatan", max_length=100, null=True, blank=True) id_village = models.CharField(verbose_name="ID Desa", max_length=40, null=True, blank=True) village = models.CharField(verbose_name="Desa", max_length=150, null=True, blank=True) manager_category = models.CharField(verbose_name="Kategori Pengelola", max_length=150, null=True, blank=True) join_date = models.DateTimeField(verbose_name="Tanggal Bergabung", null=True, blank=True) resign_date = models.DateTimeField(verbose_name="Tanggal Pengunduran Diri", null=True, blank=True) reason_resignation = models.CharField( verbose_name="Alasan Pengunduran Diri", max_length=255, null=True, blank=True) address = models.CharField(verbose_name="Alamat", max_length=255, null=True, blank=True) lt = models.CharField(max_length=50, verbose_name='lt', blank=True, null=True) lg = models.CharField(max_length=50, verbose_name='lg', blank=True, null=True) photo = models.CharField(verbose_name="Foto", max_length=150, null=True, blank=True) sv = pg_search.SearchVectorField(null=True, blank=True) menu = models.ForeignKey(MenuType, on_delete=models.CASCADE, blank=True, null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [ 'email', ] def get_complete_location_dictionary(self): province = '' districts = '' sub_district = '' village = '' id_province = '' id_districts = '' id_sub_district = '' id_village = '' if self.desa: return self.desa.get_complete_location_dictionary() return dict(province=province, districts=districts, sub_district=sub_district, village=village, id_province=id_province, id_districts=id_districts, id_sub_district=id_sub_district, id_village=id_village) # @property def get_years_birthday(self): years = "-" if self.birth_date: rdelta = relativedelta(date.today(), self.birthDate) years = rdelta.years return years return years def get_month_birthday(self): months = "-" if self.birth_date: rdelta = relativedelta(date.today(), self.birthDate) months = rdelta.months return months return months def get_day_birthday(self): days = "-" if self.birth_date: rdelta = relativedelta(date.today(), self.birthDate) days = rdelta.days return days return days def is_staff(self): "Allow All Member to Login" # Simplest possible answer: All admins are staff return self.is_active def get_full_name(self): # The user is identified by their nama if self.first_name: return self.first_name + ' ' + self.last_name else: return '' def get_alamat(self): a = "-" if self.address: a = self.address if self.desa: a = a + " " + self.desa.alamat_lengkap() return a def __str__(self): return u'%s' % (self.email) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['id'] verbose_name = 'Akun' verbose_name_plural = 'Akun'
class Content(CommonModelNameNotUnique): """A class representing a user role.""" class Meta: unique_together = [('namespace', 'repository', 'name', 'content_type')] ordering = ['namespace', 'repository', 'name', 'content_type'] indexes = [psql_indexes.GinIndex(fields=['search_vector'])] # Foreign keys # ------------------------------------------------------------------------- dependencies = models.ManyToManyField( 'Content', related_name='+', blank=True, editable=False, ) platforms = models.ManyToManyField( 'Platform', related_name='roles', verbose_name="Supported Platforms", blank=True, editable=False, ) platforms.help_text = "" cloud_platforms = models.ManyToManyField( 'CloudPlatform', related_name='roles', verbose_name="Cloud Platforms", blank=True, editable=False, ) tags = models.ManyToManyField( 'Tag', related_name='roles', verbose_name='Tags', blank=True, editable=False, ) tags.help_text = "" repository = models.ForeignKey( 'Repository', related_name='content_objects', editable=False, on_delete=models.CASCADE, ) content_type = models.ForeignKey( 'ContentType', related_name='content_objects', editable=False, on_delete=models.PROTECT, ) namespace = models.ForeignKey( 'Namespace', related_name='content_objects', on_delete=models.CASCADE, ) readme = models.ForeignKey( 'Readme', null=True, on_delete=models.SET_NULL, related_name='+', ) # Regular fields # ------------------------------------------------------------------------- # TODO(cutwater): Constants left for compatibility reasons. Should be # removed in future. ANSIBLE = constants.RoleType.ANSIBLE.value CONTAINER = constants.RoleType.CONTAINER.value CONTAINER_APP = constants.RoleType.CONTAINER_APP.value DEMO = constants.RoleType.DEMO.value role_type = models.CharField( max_length=3, choices=constants.RoleType.choices(), null=True, blank=False, default=None, editable=False, ) original_name = models.CharField(max_length=256, null=False) metadata = psql_fields.JSONField( null=False, default=dict, ) github_default_branch = models.CharField(max_length=256, default='master', verbose_name="Default Branch") container_yml = models.TextField(blank=True, null=True, verbose_name='container.yml') min_ansible_version = models.CharField( max_length=10, blank=True, null=True, verbose_name="Min Ansible Version", ) min_ansible_container_version = models.CharField( max_length=10, blank=True, null=True, verbose_name="Min Ansible Container Version", ) license = models.CharField( max_length=50, blank=True, verbose_name="License (optional)", ) company = models.CharField( max_length=50, blank=True, null=True, verbose_name="Company Name (optional)", ) is_valid = models.BooleanField( default=False, editable=False, ) featured = models.BooleanField( default=False, editable=False, ) imported = models.DateTimeField(null=True, verbose_name="Last Import") quality_score = models.FloatField( null=True, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)], ) content_score = models.FloatField( null=True, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)], ) metadata_score = models.FloatField( null=True, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)], ) compatibility_score = models.FloatField( null=True, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)], ) search_vector = psql_search.SearchVectorField() # Other functions and properties # ------------------------------------------------------------------------- def __str__(self): return "{}.{}".format(self.namespace.name, self.name) @property def github_user(self): return self.repository.github_user @property def github_repo(self): return self.repository.github_repo @property def travis_status_url(self): return self.repository.travis_status_url @property def travis_build_url(self): return self.repository.travis_build_url @property def download_count(self): return self.repository.download_count def get_absolute_url(self): return reverse('api:content_detail', args=(self.pk, )) def get_last_import(self): try: return model_to_dict(self.repository.import_tasks.latest(), fields=('id', 'state')) except Exception: return dict() def get_unique_platforms(self): return [ platform.name for platform in self.platforms.filter( active=True).order_by('name').distinct('name') ] def get_cloud_platforms(self): return [cp.name for cp in self.cloud_platforms.filter(active=True)] def get_unique_platform_versions(self): return [ platform.release for platform in self.platforms.filter( active=True).order_by('release').distinct('release') ] def get_unique_platform_search_terms(self): # Fetch the unique set of aliases terms = [] for platform in (self.platforms.filter(active=True).exclude( alias__isnull=True).exclude(alias__exact='').all()): terms += platform.alias.split(' ') return set(terms) def get_username(self): return self.namespace # TODO(cutwater): Active field is not used for tags anymore. # get_tags() function should be replaced with tags property usage and # removed as well as an `active` field from Tag model. def get_tags(self): return [tag.name for tag in self.tags.filter(active=True)] # FIXME(cutwater): Refactor me def clean(self): if self.company and len(self.company) > 50: # add_message(import_task, u"WARNING", # u"galaxy_info.company exceeds max length of 50 in meta data") self.company = self.company[:50] if not self.description: # add_message(import_task, u"ERROR", # u"missing description. Add a description to GitHub # repo or meta data.") pass elif len(self.description) > 255: # add_message(import_task, u"WARNING", # u"galaxy_info.description exceeds max length # of 255 in meta data") self.description = self.description[:255] if not self.license: # add_message(import_task, u"ERROR", # u"galaxy_info.license missing value in meta data") pass elif len(self.license) > 50: # add_message(import_task, u"WARNING", # u"galaxy_info.license exceeds max length of 50 in meta data") self.license = self.license[:50] if (not self.min_ansible_version and self.role_type in (constants.RoleType.CONTAINER, constants.RoleType.ANSIBLE)): self.min_ansible_version = u'2.4' if (not self.min_ansible_container_version and self.role_type == constants.RoleType.CONTAINER_APP): self.min_ansible_container_version = u'0.9.0'
class Mail(models.Model): PROGRESS = ( (0, "new"), (1, "processing"), (2, "done"), ) # WORKFLOW progress = models.PositiveIntegerField(choices=PROGRESS, default=0) official_response = models.PositiveIntegerField(choices=RESPONSE, default=0) assignee = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, null=True, blank=True ) # SUBMISSION INFO parent = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) # to sort by submission_date :) submission_date = models.DateTimeField(blank=True, null=True) # MAIL INFO message_id = models.CharField(max_length=1000) subject = models.CharField(max_length=1000) slug_subject = models.SlugField(max_length=1000, editable=False, default="") date = models.DateTimeField(blank=True, null=True) addresses = models.ManyToManyField( Address, related_name="addresses", through="Mail_Addresses" ) received = models.JSONField(blank=True, null=True) headers = models.JSONField(blank=True, null=True) text_plain = ArrayField( models.TextField(blank=True, null=True), blank=True, null=True ) text_html = ArrayField( models.TextField(blank=True, null=True), blank=True, null=True ) text_not_managed = ArrayField( models.TextField(blank=True, null=True), blank=True, null=True ) sender_ip_address = models.CharField(max_length=50, blank=True, null=True) to_domains = ArrayField(models.CharField(max_length=500), blank=True, null=True) # ADDITIONAL FIELDS geom = PointField(blank=True, null=True) dmark = models.TextField(blank=True, null=True) dkim = models.TextField(blank=True, null=True) spf = models.TextField(blank=True, null=True) arc = models.JSONField(blank=True, null=True) # IOC ips = models.ManyToManyField(Ip, related_name="ips") urls = models.ManyToManyField(Url, related_name="urls") attachments = models.ManyToManyField(Attachment, related_name="attachments") # TAGS tags = TaggableManager(through=CustomTag, blank=True) # STORAGE INFO eml_path = models.CharField(max_length=500, blank=True, null=True) attachments_path = models.CharField(max_length=500, blank=True, null=True) # ATTACHED REPORT reports = GenericRelation(Report, related_name="mails") taxonomy = models.IntegerField(default=0, choices=TAXONOMIES) # SEARCH FIELD search_vector = pg_search.SearchVectorField(null=True) objects = models.Manager() external_objects = MailManager() # Update search vectors works only in update def save(self, *args, **kwargs): if self._state.adding is False: self.search_vector = ( SearchVector("text_plain", weight="A", config="english") + SearchVector("text_html", weight="A", config="english") + SearchVector("subject", weight="B", config="english") ) self.slug_subject = slugify(self.subject, allow_unicode=True) super().save(*args, **kwargs) class Meta: indexes = [GinIndex(fields=["search_vector"])] @property def sender(self): sender = next(iter(self.mail_addresses_set.from_addresses()), None) if sender: flags = Flag.objects.all() suspicious_tags = [x for x in flags if x.name.find("suspicious") != -1] malicious_tags = [x for x in flags if x.name.find("malicious") != -1] return [ sender.address.tags.filter(name__in=suspicious_tags).count(), sender.address.tags.filter(name__in=malicious_tags).count(), sender.address, ] return None @property def receivers(self): try: info = InternalInfo.objects.first() except: info = None recvs = [ x.address.address for x in self.mail_addresses_set.all() if x.field in ["to", "cc", "bcc"] ] cleaned_recvs = [] if info and info.internal_domains: for x in recvs: if "@{}".format(x.split("@")[1]) in info.internal_domains: cleaned_recvs.append(x.split("@")[0]) else: cleaned_recvs.append(x) else: cleaned_recvs = recvs return [", ".join(recvs), ", ".join(cleaned_recvs)] @property def tos(self): return self.mail_addresses_set.to_addresses() @property def ccs(self): return self.mail_addresses_set.cc_addresses() @property def bccs(self): return self.mail_addresses_set.bcc_addresses() @property def reply(self): return self.mail_addresses_set.reply_to_addresses() @property def short_id(self): return truncatechars(self.message_id, 15) @property def short_subject(self): return truncatechars(self.subject, 80) @property def tag_list(self): return u", ".join(x.name for x in self.tags.all()) @property def count_iocs(self): return self.ips.count() + self.urls.count() + self.attachments.count() @property def render_iocs(self): ips = self.ips.all() ips_level = max([ip.taxonomy for ip in ips] + [0]) urls = self.urls.all() urls_level = max([url.taxonomy for url in urls] + [0]) attachments = self.attachments.all() attachments_level = max( [attachment.taxonomy for attachment in attachments] + [0] ) ioc_class = { 0: "bg-light text-dark", 1: "bg-light text-dark", 2: "bg-success", 3: "bg-warning text-dark", 4: "bg-danger", } return [ ioc_class[ips_level], ips.count(), ioc_class[urls_level], urls.count(), ioc_class[attachments_level], attachments.count(), ] def __str__(self): return truncatechars(self.subject, 80) if self.subject else ""
class Playlist(models.Model): """ An individual playlist in the media platform. """ #: Object manager. See :py:class:`~.PlaylistManager`. The objects returned by this manager do #: not include deleted objects. See :py:attr:\~.objects_including_deleted`. objects = PlaylistManager() #: Object manager whose objects include the deleted items. This has been separated out into a #: separate manager to avoid inadvertently including deleted objects in a query objects_including_deleted = PlaylistManager(include_deleted=True) #: Primary key id = models.CharField(max_length=_TOKEN_LENGTH, primary_key=True, default=_make_token, editable=False) #: Channel which contains playlist channel = models.ForeignKey('Channel', help_text='channel containing playlist', on_delete=models.CASCADE, related_name='playlist') #: Playlist title title = models.TextField(help_text='Title of the playlist', blank=False) #: Playlist description description = models.TextField(help_text='Description of the playlist', blank=True, default='') #: :py:class:`~.MediaItem` objects which make up this playlist. media_items = pgfields.ArrayField( models.CharField(max_length=_TOKEN_LENGTH), blank=True, default=_blank_array, help_text='Primary keys of media items in this playlist') #: Full text search vector field text_search_vector = pgsearch.SearchVectorField() #: Creation time created_at = models.DateTimeField(auto_now_add=True) #: Last update time updated_at = models.DateTimeField(auto_now=True) #: Deletion time. If non-NULL, the channel has been "deleted" and should not usually be #: visible. deleted_at = models.DateTimeField(null=True, blank=True) @property def ordered_media_item_queryset(self): """ A queryset which returns the media items for the play list with the same ordering as :py:attr:`.media_items`. """ all_media_items = (MediaItem.objects.filter( id__in=self.media_items).annotate(index=expressions.Func( models.Value(self.media_items), functions.Cast(models.F('id'), output_field=models.TextField()), function='array_position')).order_by('index')) return all_media_items def __str__(self): return '{} ("{}")'.format(self.id, self.title) class Meta: indexes = ( models.Index(fields=['created_at']), models.Index(fields=['updated_at']), models.Index(fields=['deleted_at']), pgindexes.GinIndex(fields=['text_search_vector']), )
class Migration(migrations.Migration): dependencies = [ ('pulp_app', '0001_initial'), ('main', '0127_drop_categories'), ] operations = [ migrations.CreateModel( name='Collection', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=64)), ('deprecated', models.BooleanField(default=False)), ('download_count', models.IntegerField(default=0.0)), ('community_score', models.FloatField(default=0.0)), ('quality_score', models.FloatField(default=0.0)), ('search_vector', psql_search.SearchVectorField(default='')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('namespace', models.ForeignKey(on_delete=models.PROTECT, to='main.Namespace')), ('tags', models.ManyToManyField(to='main.Tag')), ], ), migrations.CreateModel( name='CollectionVersion', fields=[ ('version', models.CharField(max_length=64)), ('hidden', models.BooleanField(default=False)), ('metadata', psql_fields.JSONField(default=dict)), ('contents', psql_fields.JSONField(default=dict)), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('_parent_ref', models.OneToOneField(db_column='id', on_delete=models.CASCADE, parent_link=True, primary_key=True, serialize=False, to='pulp_app.Content')), ('collection', models.ForeignKey(on_delete=models.PROTECT, related_name='versions', to='main.Collection')), ], bases=('pulp_app.content', ), ), migrations.AlterUniqueTogether( name='collectionversion', unique_together={('collection', 'version')}, ), migrations.AlterUniqueTogether( name='collection', unique_together={('namespace', 'name')}, ), migrations.AddIndex( model_name='collection', index=psql_indexes.GinIndex(fields=['search_vector'], name='main_collec_search__7ca832_gin'), ), migrations.RunPython(code=create_galaxy_repository, reverse_code=delete_galaxy_repository) ]
class MediaItem(models.Model): """ An individual media item in the media platform. Most fields in this model can store blank values since they are synced from external providers who may not have the degree of rigour we want. For the same reason, we have default values for most fields. """ @dataclasses.dataclass class Source: """An encoded media stream for a media item.""" #: MediaItem for this source (post Python3.7, we'll be able to refer to MediaItem as the #: type.) item: object #: Media type of the stream mime_type: str #: URL pointing to this source url: str #: Width of the stream or None if this is an audio stream width: typing.Optional[int] = None #: Height of the stream or None if this is an audio stream height: typing.Optional[int] = None class Meta: permissions = (('download_mediaitem', 'Can download media associated with a media item'), ) indexes = ( models.Index(fields=['created_at']), models.Index(fields=['updated_at']), models.Index(fields=['published_at']), models.Index(fields=['deleted_at']), pgindexes.GinIndex(fields=['text_search_vector']), ) VIDEO = 'video' AUDIO = 'audio' UNKNOWN = 'unknown' TYPE_CHOICES = ((VIDEO, 'Video'), (AUDIO, 'Audio')) LANGUAGE_CHOICES = tuple( itertools.chain( [('', 'None')], sorted(((language.part3, language.name) for language in languages if language.part3 != ''), key=lambda choice: choice[1]))) #: Object manager. See :py:class:`~.MediaItemManager`. The objects returned by this manager do #: not include deleted objects. See :py:attr:\~.objects_including_deleted`. objects = MediaItemManager() #: Object manager whose objects include the deleted items. This has been separated out into a #: separate manager to avoid inadvertently including deleted objects in a query objects_including_deleted = MediaItemManager(include_deleted=True) #: Primary key id = models.CharField(max_length=_TOKEN_LENGTH, primary_key=True, default=_make_token, editable=False) #: Channel which contains media item - if NULL, then the media item is in no channel. channel = models.ForeignKey('Channel', help_text='Channel containing media item', null=True, on_delete=models.SET_NULL, related_name='items') #: Media item title title = models.TextField(help_text='Title of media item', blank=True, default='') #: Media item description description = models.TextField(help_text='Description of media item', blank=True, default='') #: Duration duration = models.FloatField(editable=False, help_text='Duration of video', default=0.) #: Type of media type = models.CharField( max_length=10, choices=TYPE_CHOICES, default=UNKNOWN, editable=False, help_text='Type of media (video, audio or unknown)') #: Publication date published_at = models.DateTimeField( default=timezone.now, help_text='Date from which video is visible') #: Downloadable flag downloadable = models.BooleanField( default=False, help_text='If this item can be viewed, can it also be downloaded?') #: ISO 693-3 language code language = models.CharField( max_length=3, default='', blank=True, choices=LANGUAGE_CHOICES, help_text= ('ISO 639-3 three letter language code describing majority language used in this item' )) #: Video copyright copyright = models.TextField( blank=True, default='', help_text='Free text describing Copyright holder') #: List of tags for video tags = pgfields.ArrayField(models.CharField(max_length=256), default=_blank_array, blank=True, help_text='Tags/keywords for item') #: Full text search vector field text_search_vector = pgsearch.SearchVectorField() #: A source URL for the media. Can only be set at creation time to have any effect. If set when #: the media item is created, the URL will be fetched and transcoded. initially_fetched_from_url = models.URLField( max_length=2048, blank=True, default='', help_text= 'If set at creation time, the media item contents will be fetched from this URL' ) #: Creation time created_at = models.DateTimeField(auto_now_add=True) #: Last update time updated_at = models.DateTimeField(auto_now=True) #: Deletion time. If non-NULL, the item has been "deleted" and should not usually be visible. deleted_at = models.DateTimeField(null=True, blank=True) def __str__(self): return '{} ("{}")'.format(self.id, self.title) @cached_property def sources(self): """ A list of :py:class:`~.MediaItem.Source` instances representing the raw media sources for this media item. This list is populated irrespective of the downloadable flag. """ if not hasattr(self, 'jwp'): return [] return self.jwp.sources @cached_property def fetched_analytics(self): """ A cached property which returns legacy statistics if the media item is a legacy item. """ return self.sms.fetch_analytics() if hasattr(self, 'sms') else [] @cached_property def fetched_size(self): """ A cached property which returns the storage size of the video in bytes (the sum of all the sources). Returns 0 if the size isn't available. """ return int( getattr(getattr(getattr(self, 'jwp', {}), 'resource', {}), 'data', {}).get('size', '0'))
class CollectionVersion(Content): """ A content type representing a CollectionVersion. This model is primarily designed to adhere to the data format for Collection content. That spec is here: https://docs.ansible.com/ansible/devel/dev_guide/collections_galaxy_meta.html Fields: authors (psql_fields.ArrayField): A list of the CollectionVersion content's authors. contents (psql_fields.JSONField): A JSON field with data about the contents. dependencies (psql_fields.JSONField): A dict declaring Collections that this collection requires to be installed for it to be usable. description (models.TextField): A short summary description of the collection. docs_blob (psql_fields.JSONField): A JSON field holding the various documentation blobs in the collection. documentation (models.URLField): The URL to any online docs. homepage (models.URLField): The URL to the homepage of the collection/project. issues (models.URLField): The URL to the collection issue tracker. license (psql_fields.ArrayField): A list of licenses for content inside of a collection. name (models.CharField): The name of the collection. namespace (models.CharField): The namespace of the collection. repository (models.URLField): The URL of the originating SCM repository. version (models.CharField): The version of the collection. is_highest (models.BooleanField): Indicates that the version is the highest one in the collection. certification (models.CharField): Enum with certification status. Relations: collection (models.ForeignKey): Reference to a collection model. tag (models.ManyToManyField): A symmetric reference to the Tag objects. """ TYPE = "collection_version" CERTIFICATION_CHOICES = [ ("certified", "certified"), ("not_certified", "not_certified"), ("needs_review", "needs_review"), ] # Data Fields authors = psql_fields.ArrayField(models.CharField(max_length=64), default=list, editable=False) contents = psql_fields.JSONField(default=list, editable=False) dependencies = psql_fields.JSONField(default=dict, editable=False) description = models.TextField(default="", blank=True, editable=False) docs_blob = psql_fields.JSONField(default=dict, editable=False) documentation = models.URLField(default="", blank=True, max_length=2000, editable=False) homepage = models.URLField(default="", blank=True, max_length=2000, editable=False) issues = models.URLField(default="", blank=True, max_length=2000, editable=False) license = psql_fields.ArrayField(models.CharField(max_length=32), default=list, editable=False) name = models.CharField(max_length=64, editable=False) namespace = models.CharField(max_length=32, editable=False) repository = models.URLField(default="", blank=True, max_length=2000, editable=False) version = models.CharField(max_length=32, editable=False) is_highest = models.BooleanField(editable=False, default=False) certification = models.CharField(max_length=13, choices=CERTIFICATION_CHOICES, default="needs_review") # Foreign Key Fields collection = models.ForeignKey(Collection, on_delete=models.CASCADE, related_name="versions", editable=False) tags = models.ManyToManyField(Tag, editable=False) # Search Fields search_vector = psql_search.SearchVectorField(default="") @property def relative_path(self): """ Return the relative path for the ContentArtifact. """ return "{namespace}-{name}-{version}.tar.gz".format( namespace=self.namespace, name=self.name, version=self.version) def save(self, *args, **kwargs): """ Validates certification before save. """ certification_choices = [ value for key, value in self.CERTIFICATION_CHOICES ] if self.certification not in certification_choices: raise ValueError("Invalid certification value: '{value}'".format( value=self.certification)) super().save(*args, **kwargs) class Meta: default_related_name = "%(app_label)s_%(model_name)s" unique_together = ("namespace", "name", "version") constraints = [ UniqueConstraint( fields=("collection", "is_highest"), name="unique_is_highest", condition=Q(is_highest=True), ) ]
class Desa(models.Model): """docstring for Desa""" kecamatan = models.ForeignKey(Kecamatan, on_delete=models.CASCADE, verbose_name="Kecamatan", db_index=True) kode = models.CharField(verbose_name="Kode", max_length=6, blank=True, null=True) nama_desa = models.CharField(max_length=40, null=True, verbose_name="Nama Desa / Kelurahan", db_index=True) keterangan = models.CharField(max_length=255, blank=True, null=True, verbose_name="Keterangan") lt = models.CharField(max_length=100, null=True, blank=True, verbose_name='Latitute') lg = models.CharField(max_length=100, null=True, blank=True, verbose_name='Longitute') sv = pg_search.SearchVectorField(null=True, blank=True) def alamat_lengkap(self): return self.nama_desa + " " + self.kecamatan.nama_kecamatan + " " + self.kecamatan.kabupaten.nama_kabupaten + " " + self.kecamatan.kabupaten.provinsi.nama_provinsi def get_complete_location_dictionary(self): negara = '' provinsi = '' kabupaten = '' kecamatan = '' desa = self.nama_desa negara_id = '' provinsi_id = '' kabupaten_id = '' kecamatan_id = '' desa_id = self.id if self.kecamatan: kecamatan_id = self.kecamatan.id kecamatan = self.kecamatan.nama_kecamatan if self.kecamatan.kabupaten: kabupaten_id = self.kecamatan.kabupaten.id kabupaten = self.kecamatan.kabupaten.nama_kabupaten if self.kecamatan.kabupaten.provinsi: provinsi_id = self.kecamatan.kabupaten.provinsi.id provinsi = self.kecamatan.kabupaten.provinsi.nama_provinsi if kecamatan.kabupaten.provinsi.negara: negara_id = self.kecamatan.kabupaten.provinsi.negara.id negara = self.kecamatan.kabupaten.provinsi.negara.nama_negara return dict(negara=negara, negara_id=negara_id, provinsi=provinsi, provinsi_id=provinsi_id, kabupaten=kabupaten, kabupaten_id=kabupaten_id, kecamatan=kecamatan, kecamatan_id=kecamatan_id, desa=desa, desa_id=desa_id) def as_option(self): return "<option value='" + str(self.id) + "'>" + str( self.nama_desa) + "</option>" def as_option_desa(self): return "<option value='" + str(self.id) + "'>" + str( self.kecamatan.kabupaten.nama_kabupaten.title()) + "- Kec." + str( self.kecamatan.nama_kecamatan.title()) + "- Ds." + str( self.nama_desa.title()) + "</option>" def __unicode__(self): return "%s" % (self.nama_desa, ) class Meta: indexes = [GinIndex(fields=['sv'])] ordering = ['nama_desa'] verbose_name = "Desa / Kelurahan" verbose_name_plural = "Desa / Kelurahan"