def test_alter_text_field(self): # Regression for "BLOB/TEXT column 'info' can't have a default value") # on MySQL. new_field = TextField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field( Note, Note._meta.get_field_by_name("info")[0], new_field, strict=True, )
class IlbeArticleModel(Model): title = CharField(max_length=200) content = TextField() author = ForeignKey(get_user_model()) registed = DateTimeField() class Meta: db_table = "ilbe_articles" def __unicode__(self): return unicode(self.title)
def delete_stale_model_entries(self, model): existing_pks = ( model._default_manager.using(self.db_alias) .annotate(object_id=Cast('pk', TextField())) .values('object_id') ) content_types_pks = get_descendants_content_types_pks(model) stale_entries = ( self.entries.filter(content_type_id__in=content_types_pks) .exclude(object_id__in=existing_pks) ) stale_entries.delete()
class Libro(models.Model): isbn = models.CharField(max_length=20) titulo = models.CharField(max_length=20) descripcion = TextField(blank=True) autor = models.ForeignKey(Autor) anyo = models.IntegerField() generos = models.ManyToManyField(Genero) editorial = models.ForeignKey(Editorial) usuarios = models.ManyToManyField(Usuario, through="Puntuacion") def __unicode__(self): return self.titulo
class Li_Job(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) data_id = models.CharField(max_length=64) data_search_id = models.CharField(max_length=64) title = models.CharField(max_length=255) url = models.CharField(max_length=255) details = TextField() criteria = TextField() job = models.ForeignKey(Job, related_name="Li_jobs", on_delete=models.DO_NOTHING) poster = models.ForeignKey(Li_Poster, related_name="Li_Jobs", on_delete=models.DO_NOTHING) company = models.ForeignKey(Li_Company, related_name="Li_Jobs", on_delete=models.DO_NOTHING) post_date = models.DateTimeField() status = models.IntegerField() objects = Li_Job_Manager()
class HomePage(DiscoverUniBasePage): header = TextField(blank=True) intro = RichTextField(blank=True) course_wizard_link = TextField(blank=True) box_1_title = TextField(blank=True) box_1_content = TextField(blank=True) box_1_link = TextField(blank=True) box_2_title = TextField(blank=True) box_2_content = TextField(blank=True) box_2_link = TextField(blank=True) box_3_link = TextField(blank=True) page_links = StreamField([ ('link', blocks.StructBlock([ ('page', blocks.PageChooserBlock()), ('title', blocks.CharBlock()) ])) ]) content_panels = DiscoverUniBasePage.content_panels + [ FieldPanel('header', classname="full"), FieldPanel('intro', classname="full"), FieldPanel('course_wizard_link', classname="full"), FieldPanel('box_1_title', classname="full"), FieldPanel('box_1_content', classname="full"), FieldPanel('box_1_link', classname="full"), FieldPanel('box_2_title', classname="full"), FieldPanel('box_2_content', classname="full"), FieldPanel('box_2_link', classname="full"), FieldPanel('box_3_link', classname="full"), StreamFieldPanel('page_links', classname="full"), ] def get_context(self, request): context = super().get_context(request) context['page'] = self context['english_url'] = self.get_english_url() context['welsh_url'] = self.get_welsh_url() context['cookies_accepted'] = request.COOKIES.get('discoverUniCookies') context['load_error'] = request.GET.get('load_error', '') context['error_type'] = request.GET.get('error_type', '') context['institutions_list'] = InstitutionList.get_options()[self.get_language()] return context
def test_alter(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "CharField") self.assertEqual(bool(columns["name"][1][6]), bool(connection.features.interprets_empty_strings_as_nulls)) # Alter the name field to a TextField new_field = TextField(null=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, Author._meta.get_field_by_name("name")[0], new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertEqual(columns["name"][1][6], True) # Change nullability again new_field2 = TextField(null=False) new_field2.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertEqual(bool(columns["name"][1][6]), False)
class SiteAnnouncements(Model): """Latest site announcements""" title = CharField(max_length=150, verbose_name='Title') description = TextField(verbose_name='Description') created = DateTimeField(verbose_name='Entry Creation Date') permission_classes = ManyToManyField('PermissionClass', related_name='site_announcements', blank=True) class Meta: get_latest_by = "created" verbose_name = 'Site Announcement'
class Notify(models.Model): title = CharField(max_length=1000, blank=True, default="") subtitle = CharField(max_length=1000, blank=True, default="") info = TextField(blank=True, default="") showDate = DateTimeField() vibrate = BooleanField(default=True) song = BooleanField(default=False) def __unicode__(self): return self.title + " - " + self.subtitle
class Question(Model): question = TextField() answer1 = CharField(max_length=200) answer2 = CharField(max_length=200) answer3 = CharField(max_length=200) answer4 = CharField(max_length=200) correct_answer = CharField(max_length=200) def __str__(self): return self.question[:20] def __unicode__(self): return self.question[:20]
class QuestionGroup(models.Model): name = CharField(verbose_name="Nhóm câu hỏi", blank=False,null=False, unique=True, max_length=50) description = TextField(verbose_name = "Ghi chú", blank=True, null=True) class Meta: verbose_name = "Nhóm câu hỏi" verbose_name_plural = "Danh sách nhóm câu hỏi" def __unicode__(self): return u'%s-%s' %(self.name, self.description)
class Badges(models.Model): badge_color = RGBColorField(default='#ffffff', null=True, blank=True) badge_text_color = RGBColorField(default='#000000', null=True, blank=True) badge_text = TextField(blank=True) panels = [ FieldPanel('badge_color'), FieldPanel('badge_text_color'), FieldPanel('badge_text') ] class Meta: abstract = True
class Section(DiscoverUniBasePage): intro = RichTextField(blank=True) subsections = StreamField([ ('subsection', blocks.StructBlock([ ('subsection_title', blocks.TextBlock()), ('subsection_content', blocks.RichTextBlock(features=[ 'h3', 'h4', 'bold', 'underline', 'italic', 'embed', 'link', 'image', 'ol', 'ul', 'hr', 'blockquote' ])) ])) ]) related_links_title = TextField(blank=True) related_links = StreamField([ ('links', blocks.PageChooserBlock(required=False)), ], blank=True) lateral_link_title = TextField(blank=True) lateral_links = StreamField([ ('links', blocks.PageChooserBlock(required=False)), ], blank=True) content_panels = DiscoverUniBasePage.content_panels + [ FieldPanel('intro'), StreamFieldPanel('subsections'), FieldPanel('related_links_title'), StreamFieldPanel('related_links'), FieldPanel('lateral_link_title'), StreamFieldPanel('lateral_links') ] @property def has_lateral_links(self): return self.lateral_links or self.lateral_link_title def get_breadcrumbs(self): return self.get_ancestors().live()[1:]
class AllResourcesPage(MethodsBasePage): subpage_types = [ 'contentPages.AssetTypePage', ] parent_page_type = [ 'contentPages.HomePage' ] RESOURCE_HEADING = 'Resources' heading = TextField(default=RESOURCE_HEADING) subtitle = TextField(blank=True) banner_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) ASSET_LIST_HEADER = 'Resources List' signup_intro = TextField(blank=True) asset_list_header = TextField(default=ASSET_LIST_HEADER) content_panels = MethodsBasePage.content_panels + [ FieldPanel('heading'), FieldPanel('subtitle'), ImageChooserPanel('banner_image'), FieldPanel('signup_intro'), FieldPanel('asset_list_header'), InlinePanel('asset_types', label='Asset Types') ] def get_child_of_type(self, asset_type): children = self.get_children() for child in children: if child.specific.document_type == asset_type: return child
class BaseGeneralizationModel(Model): """Base model from which all Generalized and Specialized models inherit""" __metaclass__ = BaseGeneralizationMeta specialization_type = TextField(db_index=True) """Field to store the specialization""" def __init__(self, *args, **kwargs): """ If specialization_type is not set in kwargs, add this is the most specialized model, set specialization_type to match the specialization declared in Meta """ super(BaseGeneralizationModel, self).__init__(*args, **kwargs) # If we have a final specialization, and a specialization_type is not # specified in kwargs, set it to the default for this model: if ('specialization_type' not in kwargs and not self._meta.specializations): self.specialization_type = self.__class__.model_specialization class Meta: abstract = True def get_as_specialization(self, final_specialization=True): """ Get the specialized model instance which corresponds to the general case. :param final_specialization: Whether the specialization returned is the most specialized specialization or whether the direct specialization is used :type final_specialization: :class:`bool` :return: The specialized model corresponding to the current model """ path = self.specialization_type if not final_specialization: # We need to find the path which is only one-step down from the # current level of specialization. path = find_next_path_down(self.__class__.model_specialization, path, PATH_SEPERATOR) return self._meta.specializations[path].objects.get(pk=self.pk)
class Mingpian(Model): openid = CharField(max_length=128, null=True, unique=True) name = CharField(max_length=64, null=True, db_index=True) weixin = CharField(max_length=128, null=True) email = EmailField(null=True) phone_number = CharField(max_length=64, null=True) phone_number_2 = CharField(max_length=64, null=True) address = TextField(null=True) remark = TextField(null=True) last_update = DateTimeField(auto_now=True) validity = BooleanField(default=False) @property def summary(self): mingpian_template = u"姓名:{name}\n微信号:{weixin}\n电话:{phone_num}\n" \ u"电话2:{phone_num_2}\n邮箱:{email}\n坐标:{address}\n备注:{remark}\n" return mingpian_template.format(name=self.name, weixin=self.weixin, phone_num=self.phone_number, phone_num_2=self.phone_number_2, email=self.email, address=self.address, remark=self.remark)
class CourseFinderSummary(DiscoverUniBasePage): page_order = 8 header = TextField(blank=True) country_section_title = TextField(blank=True) mode_of_study_section_title = TextField(blank=True) subjects_section_title = TextField(blank=True) narrow_by_section_title = TextField(blank=True) content_panels = DiscoverUniBasePage.content_panels + [ FieldPanel('header', classname="full"), FieldPanel('country_section_title', classname="full"), FieldPanel('mode_of_study_section_title', classname="full"), FieldPanel('subjects_section_title', classname="full"), FieldPanel('narrow_by_section_title', classname="full") ] @property def next_page(self): return results_sibling_finder(self) @property def back_page(self): return narrow_search_sibling_finder(self)
class Message(models.Model): ensemble = ForeignKey(Ensemble) author = CharField(max_length=255, default="The NB Team<*****@*****.**>") title = CharField(max_length=512, default="untitled") body = TextField() ctime = DateTimeField(default=datetime.now) students = BooleanField(default=False) admins = BooleanField(default=False) sent = DateTimeField(default=None, null=True, blank=True) draft = BooleanField(default=False) def __unicode__(self): return "To %s on %s" % (self.ensemble.name, self.ctime)
class Availability(BaseSchedule): max_hours = models.DecimalField(max_digits=4, decimal_places=2) STATUS_CHOICES = [ (0, 'Pending'), (1, 'Approved'), (2, 'Denied') ] status = models.CharField( max_length=8, choices=STATUS_CHOICES, default=0 ) approval_date = DateTimeField(blank=True, null=True) reason = TextField(blank=True)
class GraphQLQueryForm(BootstrapMixin, forms.ModelForm): slug = SlugField() query = TextField() class Meta: model = GraphQLQuery fields = ( "name", "slug", "query", ) def get_action_url(self): return reverse("extras:graphqlquery_add")
class Blogs(models.Model): """ 博客的模型 """ title = CharField("标题", max_length=100) user = ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="作者", related_name="blogs", ) subtitle = CharField("二级标题", max_length=200, default="") content = TextField("内容", default="") classify = ForeignKey( Classify, on_delete=models.CASCADE, verbose_name="分类", related_name="blogs", null=True, ) fabulous = IntegerField(verbose_name="点赞数", default=0) created_at = models.DateTimeField(auto_now_add=True, null=False, verbose_name="创建时间") updated_at = models.DateTimeField(auto_now=True, null=False, verbose_name="修改时间") subimage = ForeignKey( UploadImages, on_delete=models.CASCADE, verbose_name="头图", related_name="subimage", ) activation = models.BooleanField("激活", default=True) def __str__(self) -> str: return str(self.title) class Meta: verbose_name = "文章" verbose_name_plural = verbose_name pass
class SubMenu(models.Model): submenu_pagelink = models.ForeignKey('wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+') submenu_title = TextField(blank=True, ) panels = [ PageChooserPanel('submenu_pagelink'), FieldPanel('submenu_title'), ] class Meta: abstract = True
class VideoUploadConfig(ConfigurationModel): """Configuration for the video upload feature.""" profile_whitelist = TextField( blank=True, help_text= "A comma-separated list of names of profiles to include in video encoding downloads." ) @classmethod def get_profile_whitelist(cls): """Get the list of profiles to include in the encoding download""" return [ profile for profile in cls.current().profile_whitelist.split(",") if profile ]
def ta_extractor(self, value): r = [] for ta in value.filter( privacidade__in=[STATUS_TA_PUBLIC, STATUS_TA_IMMUTABLE_PUBLIC ]): dispositivos = Dispositivo.objects.filter( Q(ta=ta) | Q(ta_publicado=ta)).order_by('ordem').annotate( rotulo_texto=Concat( F('rotulo'), Value(' '), F('texto'), output_field=TextField(), )).values_list('rotulo_texto', flat=True) r += list(filter(lambda x: x.strip(), dispositivos)) return ' '.join(r)
class EventProcessingException(models.Model): event = ForeignKey("Event", on_delete=models.CASCADE, null=True) data = TextField() message = CharField(max_length=500) traceback = TextField() created = DateTimeField(auto_now_add=True, editable=False) modified = DateTimeField(auto_now=True, editable=False) @classmethod def log(cls, data, exception, event): cls.objects.create( event=event, data=data or "", message=str(exception), traceback=exception_traceback.format_exc() ) def __str__(self): return smart_str("<{message}, pk={pk}, Event={event}>".format( message=self.message, pk=self.pk, event=self.event ))
class Notices(models.Model): content = TextField("内容", default="") readed = ManyToManyField( settings.AUTH_USER_MODEL, verbose_name="已读", related_name="notices_readed", null=True, ) class Meta: verbose_name = "公告" verbose_name_plural = verbose_name pass
class Manga(BaseModel): NAME_FIELD = "title" title = TextField(null=True, blank=True) alt_title = TextField(null=True, blank=True) self_url = URLField(max_length=1000, unique=True) description = TextField() status = TextField(null=True, blank=True) year = TextField(null=True, blank=True) image_url = URLField("thumbnail url", default="") # There can be manga with no chapters, i.e. future releases chapters = models.JSONField(default=dict) genres = ManyToManyField("Genre", related_name="mangas") categories = ManyToManyField("Category", related_name="mangas") author = ForeignKey("Author", related_name="mangas", on_delete=models.SET_NULL, null=True, blank=True) technical_params = models.JSONField(default=dict)
class HomePage(DiscoverUniBasePage): header = TextField(blank=True) intro = RichTextField(blank=True) page_links = StreamField([ ('link', blocks.StructBlock([('page', blocks.PageChooserBlock()), ('title', blocks.CharBlock())])) ]) content_panels = DiscoverUniBasePage.content_panels + [ FieldPanel('header', classname="full"), FieldPanel('intro', classname="full"), StreamFieldPanel('page_links', classname="full"), ]
class PersonEvent(models.Model): def __str__(self): return "{} is going to {}".format(self.person, self.event) event = ForeignKey('Event') person = ForeignKey('Person') notice = TextField(blank=True, null=True) @classmethod def serialize(cls): return json.dumps([{ 'id': p.id, 'event': p.event.name, 'person': p.person.person, 'notice': p.notice } for p in cls.objects.all()])
class Schedule(Model): """ Schedule by various departments """ name = CharField('scheduleName', max_length=256, null=False, blank=False) info = TextField('info', max_length=1000) platform = CharField('platform', max_length=256) date = DateTimeField( 'date', null=False, blank=False, help_text='Format: YYYY-MM-DDThh:mm, example 2021-01-01T15:30') department = ForeignKey(Department, on_delete=CASCADE) def __str__(self): return self.name
class CourseFinderPostcode(DiscoverUniBasePage): page_order = 7 use_skip_form = True question = TextField(blank=True) content_panels = DiscoverUniBasePage.content_panels + [ FieldPanel('question', classname="full") ] @property def next_page(self): return summary_sibling_finder(self) @property def back_page(self): return narrow_search_sibling_finder(self)
class Bank_card_detail(models.Model): driver = models.ForeignKey(Driver, on_delete=models.CASCADE, null=True, db_column='driver') name_of_card = CharField(default='', max_length=30, db_column='name_of_card') card_number = CharField(default='', max_length=30, db_column='card_number') expiry_date = CharField(default='', max_length=30, db_column='expiry_date') cvv_number = CharField(default='', max_length=3, db_column='cvv_number') billing_address = TextField(default='', db_column='billing_address') is_save = BooleanField(default=False, db_column='is_save') class Meta: db_table = 'Bank_card_details'
def __init__(self, *args, **kwargs): TextField.__init__(self, *args, **kwargs)