def contribute_to_class(self, cls, name): self.name = self.attname = name cls._meta.add_virtual_field(self) self.inherit_flag_name = INHERIT_FLAG_NAME % name self.value_field_name = VALUE_FIELD_NAME % name if not self.inherit_only: flag_field = BooleanField(default=True) flag_field.creation_counter = self.creation_counter # Adjust the creation_counter # cls.add_to_class(self.inherit_flag_name, flag_field) flag_field.contribute_to_class(cls, self.inherit_flag_name) signals.class_prepared.connect( curry(self.add_value_field, name=name), sender=cls, weak=False ) setattr(cls, name, self) display_name = 'get_%s_display' % name setattr(cls, display_name, curry(self.get_field_display, name=name)) getattr(cls, display_name).__dict__['short_description'] = name.replace('_', ' ') if not hasattr(cls, 'FIELD_INHERITANCE_MAP'): #TODO: test cls.FIELD_INHERITANCE_MAP = {} cls.FIELD_INHERITANCE_MAP[name] = (self.parent_object_field_name, self.inherited_field_name_in_parent or name) signals.class_prepared.connect(self.patch_manager, sender=cls)
def contribute_to_class(self, model, name): super(MongoUserManager, self).contribute_to_class(model, name) self.dj_model = self.model self.model = get_user_document() self.dj_model.USERNAME_FIELD = self.model.USERNAME_FIELD username = CharField(_('username'), max_length=30, unique=True) username.contribute_to_class(self.dj_model, self.dj_model.USERNAME_FIELD) self.dj_model.REQUIRED_FIELDS = self.model.REQUIRED_FIELDS for name in self.dj_model.REQUIRED_FIELDS: field = CharField(_(name), max_length=30) field.contribute_to_class(self.dj_model, name) is_staff = BooleanField(_('is_staff'), default=False) is_staff.contribute_to_class(self.dj_model, 'is_staff') is_active = BooleanField(_('is_active'), default=False) is_active.contribute_to_class(self.dj_model, 'is_active') is_superuser = BooleanField(_('is_superuser'), default=False) is_superuser.contribute_to_class(self.dj_model, 'is_superuser') last_login = DateTimeField(_('last_login'), auto_now_add=True) last_login.contribute_to_class(self.dj_model, 'last_login') date_joined = DateTimeField(_('date_joined'), auto_now_add=True) date_joined.contribute_to_class(self.dj_model, 'date_joined')
class Patient(Model): """Stores basic information for a single patient.""" # Basic identifiers first_name = CharField(max_length=32, blank=False) middle_name = CharField(max_length=32, blank=True) last_name = CharField(max_length=128, blank=False) mrn = CharField(max_length=32, unique=True) # Demographics information birthdate = DateField(null=True) gender = CharField( choices=( ('female', 'female'), ('male', 'male'), ('other', 'other or N/A'), ), max_length=16, null=True, ) # Indicates that this patient object is a test / prototype sample and not a # real patient is_sample = BooleanField() # Patient History icds = ManyToManyField(ICD, through='ICDInstance') labs = ManyToManyField(Lab, through='LabInstance') cpts = ManyToManyField(CPT, through='CPTInstance') # Also available: meds, docs def __repr__(self): fmt = '{}(first_name={}, last_name={})' cls_name = self.__class__.__name__ return fmt.format(cls_name, self.first_name, self.last_name) def __str__(self): return f'{self.last_name}, {self.first_name}'
class TaskStatus(TimeStampedModel): # TODO: rename to TaskInteraction class Meta: verbose_name = _("Task Status") verbose_name_plural = _("Task Statuses") interacted = BooleanField(default=False) # TODO: remove as mere existence of the model indicates truthfulness user = ForeignKey( settings.AUTH_USER_MODEL, related_name='interacted_tasks', # TODO: rename related_name='interactions' on_delete=CASCADE, ) task = ForeignKey( Task, related_name='task_status', # TODO: rename related_name='interactions' on_delete=CASCADE, ) def __str__(self): return f"#{self.user_id} " \ f"{'interacted' if self.interacted else 'did not interact'} " \ f"with #{self.task_id} " \ f"(#{self.pk})" def clean(self): self._validate_task_not_expired() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.full_clean() super().save(force_insert, force_update, using, update_fields) def _validate_task_not_expired(self): if self.task.expired: raise ValidationError( _("Task #%(task_id)s expired."), code=BUSINESS_LOGIC_ERROR_CODE, params={'task_id': self.task_id}, )
class User(AbstractUser): """Default user for Bug Tracker v2. """ #: First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) is_manager = BooleanField(default=False) last_viewed_project_pk = IntegerField(null=True, blank=True, default=None) notification_settings = JSONField(null=True, blank=True, default=dict) # adding custom validation to username: no '@' symbol username_validator = MyUnicodeUsernameValidator() # this is identical to the field definition in Django's AbstractUser class except for the removal of "@" from the help_text attribute. # The primary change is in the username_validator attribute above, using my customized Validator. username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and ./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) def get_pending_invitations_count(self): return self.teaminvitation_set.filter(status=1).count()
class Edital(Model): PERIODO = ( (1, '1º Período'), (2, '2º Período'), ) tipo = ForeignKey(Tipo, verbose_name='Tipo', on_delete=CASCADE) programa = ForeignKey(Programa, verbose_name='Programa', on_delete=CASCADE) numero = CharField('Número', max_length=50) sigla_uo = CharField('Unidade organizacional', max_length=100, help_text='Ex.: DG-EAD/IFRN') link_edital = URLField('URL', max_length=300, help_text='Informe o LINK onde está o edital') grupo = CharField('Grupo', max_length=200, null=True) descricao = CharField('Descrição', max_length=300) ano = PositiveIntegerField('Ano', help_text='Digite o ano') periodo = PositiveIntegerField('Período letivo', choices=PERIODO) data_publicacao = DateField('Data de publicação') existe_taxa = BooleanField('Existe taxa?', default=False) valor_taxa = DecimalField('Valor da taxa', max_digits=7, decimal_places=2) vencimento_boleto = DateField('Vencimento do boleto') anotacoes = TextField('Anotações') class Meta: verbose_name = "Edital" verbose_name_plural = "Editais" unique_together = ("numero", "sigla_uo") def nome_curto(self): return "%s %s-%s" % (self.tipo, self.numero, self.sigla_uo) nome_curto.short_description = 'Identificação' def nome_longo(self): return "%s %s" % (self.nome_curto(), self.descricao) nome_longo.short_description = 'Nome' def __str__(self): return self.nome_curto()
class User(CreatedModified, AbstractUser): uuid = UUIDField(default=uuid.uuid4, editable=False, primary_key=True) account_number = CharField(blank=True, max_length=VERIFY_KEY_LENGTH) display_name = CharField(max_length=250) github_username = CharField(blank=True, max_length=250) profile_image = URLField(blank=True, max_length=500) discord_username = CharField(blank=True, max_length=250) # Auth is_email_verified = BooleanField(default=False) class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' def __str__(self): return f'#{self.pk}: {self.display_name}' @property def username(self): return self.email @property def first_name(self): return self.display_name @first_name.setter def first_name(self, val): self.display_name = val @property def last_name(self): return None @last_name.setter def last_name(self, val): pass
class ConversationParticipant(BaseModel, UpdatedAtMixin): """The join table between Conversation and User.""" objects = ConversationParticipantQuerySet.as_manager() user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) conversation = ForeignKey(Conversation, on_delete=models.CASCADE) seen_up_to = ForeignKey( 'ConversationMessage', null=True, on_delete=models.SET_NULL, related_name='conversationparticipants_seen_up_to', ) notified_up_to = ForeignKey( 'ConversationMessage', null=True, on_delete=models.SET_NULL, related_name='conversationparticipants_notified_up_to', ) muted = BooleanField(default=False) @property def notifications(self): if self.id is None: # participant does not exist in database return ConversationNotificationStatus.NONE.value if self.muted: return ConversationNotificationStatus.MUTED.value return ConversationNotificationStatus.ALL.value def unseen_and_unnotified_messages(self): messages = self.conversation.messages.exclude_replies() if self.seen_up_to_id is not None: messages = messages.filter(id__gt=self.seen_up_to_id) if self.notified_up_to_id is not None: messages = messages.filter(id__gt=self.notified_up_to_id) return messages
class Term(Model): name = CharField( _('name'), max_length=100, unique=True, help_text=_( 'Variants of the name can be specified with a “|” separator ' '(e.g. “name|names|to name”).')) case_sensitive = BooleanField(_('case sensitive'), default=False) definition = TextField(_('definition'), blank=True, help_text=_('Accepts HTML tags.')) url = CharField(_('link'), max_length=200, blank=True, help_text=_('Address to which the term will redirect ' '(instead of redirecting to the definition).')) objects = TermManager() class Meta(object): verbose_name = _('term') verbose_name_plural = _('terms') ordering = ('name',) def __str__(self): return self.original_name def save(self, *args, **kwargs): cache.delete_many(CACHE_KEYS) super(Term, self).save(*args, **kwargs) def get_absolute_url(self): if self.url: return self.url return reverse('term', kwargs={'pk': self.pk}) def name_variants(self, variant_slice=slice(0, None)): return self.name.replace('&', '&').split('|')[variant_slice] @property def original_name(self): return self.name_variants(0)
class Education(Model): HSI = "HSI" HS = "HS" AS = "AS" AAS = "AAS" BS = "BS" BA = "BA" MS = "MS" MA = "MA" PH = "Phd" DEGREE_CHOICES = ( (HSI, "Incomplete High School"), (HS, "High School"), (AS, "Associate of Science"), (AAS, "Associate of Applied Science"), (BS, "Bachelor of Science"), (BA, "Bachelor of Arts"), (MS, "Masters of Science"), (MA, "Masters of Arts"), (PH, "Doctorate"), ) degree_type = CharField( max_length=3, choices=DEGREE_CHOICES, ) degree = CharField(max_length=100) slug = AutoSlugField(max_length=50, populate_from=["id", "degree_type"]) institution = CharField(max_length=250) started_at = DateField() ended_at = DateField(blank=True, null=True) current = BooleanField() class Meta: ordering = ("-ended_at", "-started_at") def __str__(self): return (f"{self.degree_type} at {self.institution.name}")
def annotate_is_complete(self, queryset): """Add an annotation to a queryset to specify if an Asset is complete or not""" return queryset.annotate(is_complete=Case(When(Q( Q(name__isnull=False), Q( department__isnull=False), Q(purpose__isnull=False), Q( Q(purpose='research', owner__isnull=False) | ~Q(purpose='research')), Q( Q(purpose='other', purpose_other__isnull=False) | ~Q(purpose='other')), Q( Q(personal_data=False) | Q(Q(personal_data=True), ~Q(data_subject=[]), ~Q(data_category=[]), recipients_outside_uni__isnull=False, recipients_outside_eea__isnull=False, retention__isnull=False)), Q( Q(recipients_outside_uni='yes', recipients_outside_uni_description__isnull=False) | ~Q(recipients_outside_uni='yes')), Q( Q(recipients_outside_eea='yes', recipients_outside_eea_description__isnull=False) | ~Q(recipients_outside_eea='yes')), ~Q(risk_type=[]), Q(storage_location__isnull=False), ~Q(storage_format=[]), Q(~Q(storage_format__contains='paper') | Q(Q(storage_format__contains='paper'), ~Q( paper_storage_security=[]))), Q(~Q(storage_format__contains='digital') | Q(Q(storage_format__contains='digital'), ~Q( digital_storage_security=[])))), then=Value(True)), default=Value(False), output_field=BooleanField()))
class LoginInfor(CoreModel): session_id = CharField(max_length=64, verbose_name="会话标识", null=True, blank=True) browser = CharField(max_length=64, verbose_name="浏览器") ipaddr = CharField(max_length=32, verbose_name="ip地址", null=True, blank=True) loginLocation = CharField(max_length=64, verbose_name="登录位置", null=True, blank=True) msg = TextField(verbose_name="操作信息", null=True, blank=True) os = CharField(max_length=64, verbose_name="操作系统", null=True, blank=True) status = BooleanField(default=False, verbose_name="登录状态") class Meta: verbose_name = '登录日志' verbose_name_plural = verbose_name def __str__(self): return f"{self.creator and self.creator.name}"
class JNF(Model): class Meta: permissions = [ ('apply_jnf', 'Can apply for the job notified by jnf'), ('approve_jnf', 'Can approve jnf'), ] company = ForeignKey(Company, on_delete=PROTECT, related_name='jnf', related_query_name='jnf') min_ctc = CharField("Minimum CTC offered (annual)", null=True, blank=True, max_length=32) city = CharField("City(Cities) of Posting", max_length=40) designation = CharField(max_length=20) job_description = CharField( max_length=1000, null=True, blank=True, ) skills_required = CharField( max_length=255, null=True, blank=True, ) remarks = CharField( max_length=255, null=True, blank=True, ) approved = BooleanField(null=False, default=False, blank=True) def get_absolute_url(self): return reverse("recruiters:jnf_detail", kwargs={'pk': self.pk})
class UserChannel(Model): """ This class represents a chat message. It has a owner (user), timestamp and the message body. """ user = ForeignKey(get_user_model(), on_delete=CASCADE, verbose_name='user', db_index=True) channel = CharField(max_length=150) room = CharField(max_length=150, null=True, blank=True) created = DateTimeField(auto_now_add=True, editable=False, db_index=True) last_seen = DateTimeField(auto_now=True) status = BooleanField(default=True) def change_status(self): self.status = not self.status self.save(update_fields=['status']) # Inform client there is a new message. notification = { 'type': 'operator_status_changed', 'user': self.user.pk, 'status': self.status } channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(self.room, notification) # Meta class Meta: verbose_name = 'Canale Utente' verbose_name_plural = 'Canali Utenti' ordering = ('-created',)
class Client(Model): name = CharField(max_length=255, verbose_name="ScrapydClient") ip = CharField(max_length=255, verbose_name="ip地址") port = IntegerField(default=6800, verbose_name="端口") desc = TextField(blank=True, null=True, verbose_name="说明") auth = BooleanField(default=False, verbose_name="是否授权") # auth = IntegerField(default=0, blank=True, null=True, verbose_name="授权") username = CharField(max_length=255, blank=True, null=True, verbose_name="用户名") password = CharField(max_length=255, blank=True, null=True, verbose_name="密码") created_at = DateTimeField(auto_now_add=True, verbose_name="创建时间") updated_at = DateTimeField(auto_now=True, verbose_name="更新时间") class Meta: verbose_name = 'Scrapyd客户端' verbose_name_plural = verbose_name def __str__(self): return self.name
class HLSPlaybackEnabledFlag(ConfigurationModel): """ Enables HLS Playback across the platform. When this feature flag is set to true, individual courses must also have HLS Playback enabled for this feature to take effect. """ # this field overrides course-specific settings enabled_for_all_courses = BooleanField(default=False) @classmethod def feature_enabled(cls, course_id): """ Looks at the currently active configuration model to determine whether the HLS Playback feature is available. If the feature flag is not enabled, the feature is not available. If the flag is enabled for all the courses, feature is available. If the flag is enabled and the provided course_id is for an course with HLS Playback enabled, the feature is available. Arguments: course_id (CourseKey): course id for whom feature will be checked. """ if not HLSPlaybackEnabledFlag.is_enabled(): return False elif not HLSPlaybackEnabledFlag.current().enabled_for_all_courses: feature = (CourseHLSPlaybackEnabledFlag.objects.filter( course_id=course_id).order_by('-change_date').first()) return feature.enabled if feature else False return True def __unicode__(self): current_model = HLSPlaybackEnabledFlag.current() return u"HLSPlaybackEnabledFlag: enabled {is_enabled}".format( is_enabled=current_model.is_enabled())
class Dog(Model): MALE = "m" FEMALE = "f" name = CharField(max_length=256, null=False) sex = CharField(max_length=1, choices=( (MALE, "Male"), (FEMALE, "Female") ), null=False) age = IntegerField(null=False) breed = CharField(max_length=256, null=True) bio = TextField(null=True) location = ForeignKey(Location, on_delete=CASCADE, null=False) personality = ForeignKey(PersonalityQualities, on_delete=CASCADE, null=False) physical = ForeignKey(PhysicalQualities, on_delete=CASCADE, null=False) has_shelter = BooleanField(default=False, null=False) owner = ForeignKey(UserProfile, on_delete=CASCADE, null=True, blank=True) shelter = ForeignKey(Shelter, on_delete=CASCADE, null=True, blank=True) def __str__(self): return 'Dog: {}, {}, {}, {}'.format(self.name, self.sex, self.age, self.breed)
class Project(models.Model): # Fields name = CharField(max_length=255) slug = AutoSlugField(populate_from='name', blank=True) created = DateTimeField(auto_now_add=True, editable=False) last_updated = DateTimeField(auto_now=True, editable=False) date_started = DateField() date_ended = DateField(null=True, blank=True) description = TextField(blank=True, null=True) url = CharField(max_length=255, null=True, blank=True) is_current = BooleanField() class Meta: ordering = ('-created', ) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('resume_project_detail', args=(self.slug, )) def get_update_url(self): return reverse('resume_project_update', args=(self.slug, ))
class OverviewPage(TitleSlugDescriptionModel, UUIDModel): """ An overview page shows up as a main item in the top navigation menu and allows linking together of other objects. """ detail_page_markdown = TextField(blank=True) algorithms = ManyToManyField("algorithms.Algorithm", blank=True) archives = ManyToManyField("archives.Archive", blank=True) challenges = ManyToManyField("challenges.Challenge", blank=True) reader_studies = ManyToManyField("reader_studies.ReaderStudy", blank=True) published = BooleanField(default=False) class Meta(TitleSlugDescriptionModel.Meta, UUIDModel.Meta): ordering = ("-created", ) indexes = (Index(fields=["published"]), ) def __str__(self): return self.title def get_absolute_url(self): return reverse("overview-pages:detail", kwargs={"slug": self.slug})
def board(self): Role = apps.get_model("user", "Role") return ( super() .get_queryset() .annotate( role_name=Subquery( Role.objects.filter( user_id=OuterRef("id"), ends_at__isnull=True ).values("division__name")[:1], output_field=CharField(), ), role_is_head=Subquery( Role.objects.filter( user_id=OuterRef("id"), ends_at__isnull=True, division__name=OuterRef("role_name"), ).values("is_head")[:1], output_field=BooleanField(), ), ) .filter(role_name__isnull=False) .order_by("name", "surname") )
class Message(Model): class Meta: ordering = ['-created'] id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) thread = ForeignKey(Thread, related_name="messages", on_delete=CASCADE) alias = OneToOneField("Message", null=True, related_name="related_message", on_delete=CASCADE) sender = ForeignKey(User, verbose_name="Author", related_name="messages", on_delete=CASCADE) public_key_owner = ForeignKey(User, verbose_name="Public Key Owner", related_name="messages_by_pb_key", on_delete=CASCADE) text = TextField(verbose_name="Message text", max_length=4096) read = BooleanField(verbose_name="Read", default=False) created = DateTimeField(auto_now_add=True) def __str__(self): return str(self.id)
def _try_breadth_first(self, tasks): """Try to find tasks with maximum amount of annotations, since we are trying to label tasks as fast as possible """ # ======= # This commented part is trying to solve breadth-first in a bit different way: # it selects first task where any amount of annotations have been already created # we've left it here to be able to select it through the project settings later # ======= # annotations = Annotation.objects.filter(task=OuterRef('pk'), ground_truth=False) # not_solved_tasks_labeling_started = tasks.annotate(labeling_started=Exists(annotations)) # not_solved_tasks_labeling_started_true = not_solved_tasks_labeling_started.filter(labeling_started=True) # if not_solved_tasks_labeling_started_true.exists(): # # try to complete tasks that are already in progress # next_task = self._get_random(not_solved_tasks_labeling_started_true) # return next_task tasks = tasks.annotate(annotations_count=Count('annotations')) max_annotations_count = tasks.aggregate( Max('annotations_count'))['annotations_count__max'] if max_annotations_count == 0: # there is no any labeled tasks found return # find any task with maximal amount of created annotations not_solved_tasks_labeling_started = tasks.annotate( reach_max_annotations_count=Case(When( annotations_count=max_annotations_count, then=Value(True)), default=Value(False), output_field=BooleanField())) not_solved_tasks_labeling_with_max_annotations = not_solved_tasks_labeling_started.filter( reach_max_annotations_count=True) if not_solved_tasks_labeling_with_max_annotations.exists(): # try to complete tasks that are already in progress return self._get_random_unlocked( not_solved_tasks_labeling_with_max_annotations)
class Conference(Model): conference_name = CharField(max_length=128) conference_slug = SlugField() status = CharField(choices=conference_statuses, max_length=50, default='upcoming') accepting_bids = BooleanField(default=False) act_style = CharField(choices=act_format, max_length=50, default='normal') def __unicode__(self): return self.conference_name @classmethod def current_conf(cls): return cls.objects.filter(status__in=('upcoming', 'ongoing')).first() @classmethod def by_slug(cls, slug): try: return cls.objects.get(conference_slug=slug) except cls.DoesNotExist: return cls.current_conf() @classmethod def all_slugs(cls): return cls.objects.order_by('-conference_slug').values_list( 'conference_slug', flat=True) def windows(self): from gbe.models import VolunteerWindow return VolunteerWindow.objects.filter(day__conference=self) class Meta: verbose_name = "conference" verbose_name_plural = "conferences" app_label = "gbe"
def apply(self, tests): """ Convert JSON logic to queryset info, returns an Q object and fills self.annotations """ if not tests: return Q() if isinstance(tests, bool): # not really a legal configuration but used in the test suite return Value(tests, output_field=BooleanField()) operator = list(tests.keys())[0] values = tests[operator] # Easy syntax for unary operators, like {"var": "x"} instead of strict # {"var": ["x"]} if not isinstance(values, list) and not isinstance(values, tuple): values = [values] if operator in self.bool_ops: return self.bool_ops[operator](*[self.apply(v) for v in values]) elif operator in self.comparison_ops: return self.comparison_ops[operator](*values) else: raise ValueError(f'Invalid operator {operator} on first level')
class Role(CoreModel): DATASCOPE_CHOICES = ( ('1', "全部数据权限"), ('2', "自定数据权限"), ('3', "本部门数据权限"), ('4', "本部门及以下数据权限"), ('5', "仅本人数据权限"), ) roleName = CharField(max_length=64, verbose_name="角色名称") roleKey = CharField(max_length=64, verbose_name="权限字符") roleSort = IntegerField(verbose_name="角色顺序") status = CharField(max_length=8, verbose_name="角色状态") admin = BooleanField(default=False, verbose_name="是否为admin") dataScope = CharField(max_length=8,default='1', choices=DATASCOPE_CHOICES, verbose_name="权限范围",) remark = TextField(verbose_name="备注", help_text="备注", null=True, blank=True) dept = ManyToManyField(to='permission.Dept', verbose_name='数据权限-关联部门', db_constraint=False) menu = ManyToManyField(to='permission.Menu', verbose_name='关联菜单权限', db_constraint=False) class Meta: verbose_name = '角色管理' verbose_name_plural = verbose_name def __str__(self): return f"{self.roleName}"
def notes(request, category_id=None): context = {} categories = Category.objects.all() notes_qs = (Note.objects.filter(status=Note.STATUS_PUBLISHED).annotate( is_favorite=Case( When(favorites__user__id=request.user.id, then=Value(True)), default=Value(False), output_field=BooleanField(), )).values('slug', 'title', 'is_favorite')) if category_id: category = get_object_or_404(Category, id=category_id) notes_qs = notes_qs.filter(category=category) context['category_id'] = int(category_id) notes_list = list(notes_qs) notes_draft = DraftNote.objects.filter(user=request.user) context.update({ 'notes': json.dumps(notes_list), 'notes_draft': notes_draft, 'categories': categories, }) return render(request, template_name='notes/notes.html', context=context)
def get_problematic_tweet_relations(annotator_id:int): from django.db.models import Case, When, Value, BooleanField IN_PROGRESS_IDS = get_ids_in_cache('RESOLVE_TWEET_RELATION') subquery_ = Annotation.objects.filter( tweet_relation=OuterRef('id'), annotator=annotator_id ) queryset = TweetRelation.objects \ .filter(relevant=True, problematic=True) \ .exclude(id__in=IN_PROGRESS_IDS) \ .annotate( is_skipped_ANNOTATED=Case( When(revision__skipped=True, then=Value(True)), default=Value(False), output_field=BooleanField() ), has_been_annotated_by_user_ANNOTATED=Exists( subquery_ ), has_revision_ANNOTATED=Exists( Revision.objects.filter( tweet_relation=OuterRef('id'), ) ), has_revision_without_annotation_ANNOTATED=Exists( Revision.objects.filter( tweet_relation=OuterRef('id'), annotation=None ) ) ) \ .only('id') return list(queryset)
class RelevancyBaseModel(Model, MessagesMixin): is_relevant = BooleanField(default=False) relevancy_exception = CharField(blank=True, max_length=255, verbose_name='exception') @property def may_be_relevant(self): return True @property def relevancy_warnings(self): return '' relevancy_warnings.fget.short_description = 'warnings' @property def relevancy_errors(self): return '' relevancy_errors.fget.short_description = 'errors' class Meta: abstract = True
class User(BaseUser, ClassStr): company = ForeignKey('Company', on_delete=models.CASCADE, null=True, blank=True) is_admin = BooleanField(default=False) email = CIEmailField('email', unique=True, blank=False) objects = BaseUserManager() def clean(self, *args, **kwargs): super().clean() # Validate company and is_admin not both set if self.company and self.is_admin: raise ValidationError("Company and is_admin cannot set both") def save(self, *args, **kwargs): # If this is a new user if not self.pk and not self.password: password = User.objects.make_random_password() self.set_password(password) self.full_clean() super().save(*args, **kwargs)
def _build_filename_contains_raw_query(field, value): # It is not possible to use Django's ORM to query for if one item in a JSONB # list has has a key which contains a specified value. # # The closest thing the Django ORM provides is: # queryset.filter(your_json_field__contains=[{"key":"value"}]) # However this is an exact match, so in the above example [{"key":"value_etc"}] # would not match the filter. # # Instead we have to resort to RawSQL to use various built in PostgreSQL JSON # Array manipulation functions to be able to 'iterate' over a JSONB list # performing `like` on individual keys in said list. num_files_with_name_like_value = f""" EXISTS( SELECT attached_files ->> 'visible_name' FROM JSONB_ARRAY_ELEMENTS("field_{field.id}") as attached_files WHERE UPPER(attached_files ->> 'visible_name') LIKE UPPER(%s) ) """ return RawSQL( num_files_with_name_like_value, params=[f"%{value}%"], output_field=BooleanField(), )
class Client(Model): """ Scrapyd Server """ name = CharField(max_length=100) ip = CharField(max_length=100) port = IntegerField(default=6800) auth = BooleanField(default=False) username = CharField(max_length=100, blank=True, null=True, default=None) password = CharField(max_length=100, blank=True, null=True, default=None) created_at = DateTimeField(auto_now_add=True) updated_at = DateTimeField(default=timezone.now) spider_amount = IntegerField(default=0) def __str__(self): """ to string :return: name """ return self.name def remove_spider(self, amount): """ remove spider :param amount: amount of spider """ self.spider_amount -= amount self.save() def add_spider(self, amount): """ add spider :param amount: amount of spider """ self.spider_amount += amount self.save()
class GraphSession(models.Model): created = DateTimeField('created', default=timezone.now) listidx = IntegerField(default=0) title = CharField(max_length=200, default="", blank=True, null=True) description = TextField(blank=True, null=True) loglines = TextField(blank=True, null=True) logheader = TextField(blank=True, null=True) example = BooleanField(default=False) excomment = CharField(max_length=200, default="", blank=True, null=True) username = CharField(max_length=200) quicksaved = DateTimeField('quicksaved', blank=True, null=True) stashed = DateTimeField('stashed', blank=True, null=True) graphdef = TextField(blank=True) # stashed live data on top of quicksave stashed_pickle = TextField(blank=True) stashed_matfile = CharField(max_length=200, default="", blank=True) # restore point / quick save quicksave_pickle = TextField(blank=True) quicksave_matfile = CharField(max_length=200, default="", blank=True) def __str__(self): return 'session %s, idx %s, %s' % (self.id, self.listidx, self.title) def reset(self): self.stashed_pickle = "reset" self.quicksave_pickle = "reset" self.loglines = "" self.logheader = "" self.stashed_matfile = "" self.quicksave_matfile = ""