Python django.db.models.CharField() Examples

The following are code examples for showing how to use django.db.models.CharField(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: openhatch   Author: campbe13   File: 0001_initial.py    GNU Affero General Public License v3.0 10 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Project'
        db.create_table('search_project', (
            ('id', models.AutoField(primary_key=True)),
            ('language', models.CharField(max_length=200)),
            ('name', models.CharField(max_length=200)),
        ))
        db.send_create_signal('search', ['Project'])
        
        # Adding model 'Bug'
        db.create_table('search_bug', (
            ('project', models.ForeignKey(orm.Project)),
            ('status', models.CharField(max_length=200)),
            ('description', models.TextField()),
            ('id', models.AutoField(primary_key=True)),
            ('title', models.CharField(max_length=200)),
        ))
        db.send_create_signal('search', ['Bug']) 
Example 2
Project: fleeg-platform   Author: Fleeg   File: search.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def process_query(q_filter_link=None, q_filter_user=None, level=None):
        level_results = []

        if level is None:
            level = {'link': Q(), 'user': Q()}

        if q_filter_link:
            level_results += Post.objects.filter(q_filter_link, level['link']).annotate(
                result_type=Value('post', CharField())).order_by('-created_at')
        if q_filter_user:
            level_results += Account.objects.filter(q_filter_user, level['user']).annotate(
                result_type=Value('user', CharField())).order_by('-created_at')

        if q_filter_link and q_filter_user:
            level_results = sorted(level_results, key=lambda item: item.created_at, reverse=True)
        return level_results 
Example 3
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_title_field(self):
        """
        The model should have a title field
        """
        field = OmniFormBase._meta.get_field('title')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 4
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_form_class(self):
        """
        The _get_form_class method should return a form class
        """
        form_class = self.omniform.get_form_class()
        self.assertTrue(issubclass(form_class, OmniFormBaseForm))
        self.assertEqual(form_class.__name__, 'OmniFormTestModel')
        form = form_class()

        # Test the title field
        self.assertIsInstance(form.fields['title'], forms.CharField)
        self.assertIsInstance(form.fields['title'].widget, forms.TextInput)
        self.assertEqual(form.fields['title'].label, 'Please give us a title')
        self.assertEqual(form.fields['title'].initial, 'Some title...')
        self.assertTrue(form.fields['title'].required)

        # Test the agree field
        self.assertIsInstance(form.fields['agree'], forms.BooleanField)
        self.assertIsInstance(form.fields['agree'].widget, forms.CheckboxInput)
        self.assertEqual(form.fields['agree'].label, 'Please agree')
        self.assertTrue(form.fields['agree'].initial)
        self.assertTrue(form.fields['agree'].required) 
Example 5
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_fields(self):
        """
        The method should return the correct fields as a dict
        """
        fields = self.omniform._get_fields()
        self.assertEqual(2, len(fields))

        # Test the title field
        self.assertIsInstance(fields['title'], forms.CharField)
        self.assertIsInstance(fields['title'].widget, forms.TextInput)
        self.assertEqual(fields['title'].label, 'Please give us a title')
        self.assertEqual(fields['title'].initial, 'Some title...')
        self.assertTrue(fields['title'].required)

        # Test the agree field
        self.assertIsInstance(fields['agree'], forms.BooleanField)
        self.assertIsInstance(fields['agree'].widget, forms.CheckboxInput)
        self.assertEqual(fields['agree'].label, 'Please agree')
        self.assertTrue(fields['agree'].initial)
        self.assertTrue(fields['agree'].required) 
Example 6
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 6 votes vote down vote up
def test_get_field(self):
        """
        The _get_field method should return a form field instance
        """
        field_1 = self.omniform._get_field('title')
        field_2 = self.omniform._get_field('agree')
        field_3 = self.omniform._get_field('fictional')
        self.assertIsInstance(field_1, forms.CharField)
        self.assertIsInstance(field_1.widget, forms.TextInput)
        self.assertEqual(field_1.label, 'Please give us a title')
        self.assertTrue(field_1.required)
        self.assertIsInstance(field_2, forms.BooleanField)
        self.assertIsInstance(field_2.widget, forms.CheckboxInput)
        self.assertEqual(field_2.label, 'Please agree')
        self.assertTrue(field_2.required)
        self.assertIsNone(field_3) 
Example 7
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_overriding_parse_empty_string_as_none_in_shortcut():
    from tests.models import Foo

    from django.db.models import CharField

    s = Shortcut(
        call_target=Field.text,
        parse_empty_string_as_none='foo',
    )
    # test overriding parse_empty_string_as_none
    x = member_from_model(
        cls=Field,
        model=Foo,
        model_field=CharField(blank=True),
        factory_lookup={CharField: s},
        factory_lookup_register_function=register_field_factory,
        defaults_factory=field_defaults_factory,
    )

    assert 'foo' == x.parse_empty_string_as_none 
Example 8
def backwards(self, orm):
        
        # Adding field 'Person.username'
        db.add_column('profile_person', 'username', models.CharField(max_length=200))
        
        # Adding field 'Person.name'
        db.add_column('profile_person', 'name', models.CharField(max_length=200))
        
        # Adding field 'Person.password_hash_md5'
        db.add_column('profile_person', 'password_hash_md5', models.CharField(max_length=200))
        
        # Changing field 'Person.user'
        db.alter_column('profile_person', 'user_id', models.ForeignKey(orm['auth.User']))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 18, 686204)))
        
        # Changing field 'Link_Person_Tag.time_record_was_created'
        db.alter_column('profile_link_person_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 20, 261274)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 16, 979526)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 7, 10, 15, 5, 18, 164561))) 
Example 9
Project: openhatch   Author: campbe13   File: 0014_asheesh_add_interested_in_field_to_person.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_Project_Tag'
        db.create_table('profile_link_project_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 20, 14, 24, 45, 825148))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_Project_Tag'])
        
        # Adding field 'Person.interested_in_working_on'
        db.add_column('profile_person', 'interested_in_working_on', models.CharField(default='', max_length=1024))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 20, 14, 24, 45, 737449)))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 20, 14, 24, 45, 527201))) 
Example 10
Project: openhatch   Author: campbe13   File: 0007_tag_type_remove_s.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'TagType'
        db.create_table('profile_tagtype', (
            ('id', models.AutoField(primary_key=True)),
            ('prefix', models.CharField(max_length=20)),
        ))
        db.send_create_signal('profile', ['TagType'])
        
        # Deleting model 'tagtypes'
        db.delete_table('profile_tagtypes')
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 12, 52, 616983)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 12, 53, 45500))) 
Example 11
Project: openhatch   Author: campbe13   File: 0007_tag_type_remove_s.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def backwards(self, orm):
        
        # Deleting model 'TagType'
        db.delete_table('profile_tagtype')
        
        # Adding model 'tagtypes'
        db.create_table('profile_tagtypes', (
            ('prefix', models.CharField(max_length=20)),
            ('id', models.AutoField(primary_key=True)),
        ))
        db.send_create_signal('profile', ['tagtypes'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 5, 403945)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 5, 292717))) 
Example 12
Project: openhatch   Author: campbe13   File: 0022_asheesh_add_person_tag_link.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_Person_Tag'
        db.create_table('profile_link_person_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('project', models.ForeignKey(orm.Person)),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 25, 66622))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_Person_Tag'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 24, 174516)))
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 24, 576063)))
        
        # Changing field 'Link_Project_Tag.time_record_was_created'
        db.alter_column('profile_link_project_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 29, 0, 21, 24, 667481))) 
Example 13
Project: django-atom   Author: ad-m   File: generate_factory.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_creator_for_field(self, name, field, model):
        if isinstance(field, models.AutoField):
            return False
        if isinstance(field, models.ForeignKey):
            return 'factory.SubFactory("{}")'.format(self.get_subfactory_path(field.related_model))
        if isinstance(field, models.CharField):
            return 'factory.Sequence("{0}-{1}-{{0}}".format)'.format(self.safe_name(model.__name__), self.safe_name(name))
        if isinstance(field, models.TextField):
            return "factory.fuzzy.FuzzyText()"
        if isinstance(field, (models.BooleanField, models.NullBooleanField)):
            return "factory.Sequence(lambda n: n % 2 == 0)"
        if isinstance(field, (models.IntegerField, models.SmallIntegerField)):
            return "factory.Sequence(lambda n: n)"
        if isinstance(field, (models.DateTimeField)):
            if field.__class__.__name__ in ['AutoLastModifiedField', 'AutoCreatedField']:  # django-model-utils fields
                return False
            return "factory.fuzzy.FuzzyNaiveDateTime(datetime.datetime(2008, 1, 1))"
        return "UNKNOWN  # TODO: {}".format(field.__class__.__name__) 
Example 14
Project: django-idcops   Author: Wenvki   File: utils.py    Apache License 2.0 6 votes vote down vote up
def allow_search_fields(cls, exclude=None):
    opts = cls._meta
    if not exclude:
        exclude = ['onidc', 'slug', 'created', 'modified']
    exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])
    fields = []
    for f in opts.fields:
        if exclude and f.name in exclude:
            continue
        if isinstance(f, models.ForeignKey):
            submodel = f.related_model
            for sub in submodel._meta.fields:
                if exclude and sub.name in exclude:
                    continue
                if isinstance(sub, models.CharField) \
                        and not getattr(sub, 'choices'):
                    fields.append(f.name + '__' + sub.name + '__icontains')
        if isinstance(f, models.CharField):
            fields.append(f.name + '__icontains')
    return fields 
Example 15
Project: django-translations   Author: bbmokhtari   File: models.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_translatable_fields(cls):
        """Return the model’s translatable fields."""
        if not hasattr(cls, '_cached_translatable_fields'):
            if cls.TranslatableMeta.fields is None:
                fields = []
                for field in cls._meta.get_fields():
                    if isinstance(
                                field,
                                (models.CharField, models.TextField,)
                            ) and not isinstance(
                                field,
                                models.EmailField
                            ) and not (
                                hasattr(field, 'choices') and field.choices
                            ):
                        fields.append(field)
            else:
                fields = [
                    cls._meta.get_field(field_name)
                    for field_name in cls.TranslatableMeta.fields
                ]
            cls._cached_translatable_fields = fields
        return cls._cached_translatable_fields 
Example 16
Project: data-workspace   Author: uktrade   File: models.py    MIT License 6 votes vote down vote up
def get_form_field(self):
        """
        Instantiates a form field based on this models selected `data_type`.
        Falls back to `CharField` if not found.
        :return:
        """
        field_data = {'label': self.name}
        if self.data_type == self.DATA_TYPE_DATE:
            field_data['widget'] = forms.DateInput(attrs={'type': 'date'})
        elif self.data_type == self.DATA_TYPE_TIME:
            field_data['widget'] = forms.DateInput(attrs={'type': 'time'})
        elif self.data_type == self.DATA_TYPE_FOREIGN_KEY:
            field_data['queryset'] = self.linked_reference_dataset.get_records()
        field_data['required'] = self.is_identifier or self.required
        field = self._DATA_TYPE_FORM_FIELD_MAP.get(self.data_type)(**field_data)
        field.widget.attrs['required'] = field.required
        return field 
Example 17
Project: xadmin_bugfix   Author: vip68   File: filters.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 18
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 19
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 20
Project: django-xadmin   Author: MarkHoo   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
            isinstance(field, models.CharField)
            and field.max_length > 20
            or isinstance(field, models.TextField)
        ) 
Example 21
Project: omni-forms   Author: omni-digital   File: models.py    MIT License 5 votes vote down vote up
def get_concrete_class_for_model_field(cls, model_field):
        """
        Method for getting a concrete model class to represent the type of form field required

        :param model_field: Model Field instance
        :return: OmniField subclass
        """
        field_mapping = {
            models.CharField: OmniCharField,
            models.TextField: OmniCharField,
            models.BooleanField: OmniBooleanField,
            models.NullBooleanField: OmniBooleanField,
            models.DateField: OmniDateField,
            models.DateTimeField: OmniDateTimeField,
            models.DecimalField: OmniDecimalField,
            models.EmailField: OmniEmailField,
            models.FloatField: OmniFloatField,
            models.IntegerField: OmniIntegerField,
            models.BigIntegerField: OmniIntegerField,
            models.PositiveIntegerField: OmniIntegerField,
            models.PositiveSmallIntegerField: OmniIntegerField,
            models.SmallIntegerField: OmniIntegerField,
            models.CommaSeparatedIntegerField: OmniCharField,
            models.TimeField: OmniTimeField,
            models.URLField: OmniUrlField,
            models.ForeignKey: OmniForeignKeyField,
            models.ManyToManyField: OmniManyToManyField,
            models.SlugField: OmniSlugField,
            models.FileField: OmniFileField,
            models.ImageField: OmniImageField,
            models.DurationField: OmniDurationField,
            models.GenericIPAddressField: OmniGenericIPAddressField
        }
        field_mapping.update(cls.get_custom_field_mapping())
        return field_mapping.get(model_field.__class__) 
Example 22
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_label_field(self):
        """
        The model should have a label field
        """
        field = OmniField._meta.get_field('label')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 23
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_widget_class_field(self):
        """
        The model should have a widget_class field
        """
        field = OmniField._meta.get_field('widget_class')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 24
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_get_concrete_class_for_model_field(self):
        """
        The get_concrete_class_for_model_field method should return the correct OmniField subclass
        """
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.CharField()), OmniCharField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.NullBooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BooleanField()), OmniBooleanField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DateTimeField()), OmniDateTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DecimalField()), OmniDecimalField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.EmailField()), OmniEmailField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FloatField()), OmniFloatField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.IntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.BigIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.PositiveIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SmallIntegerField()), OmniIntegerField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.TimeField()), OmniTimeField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.URLField()), OmniUrlField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.SlugField()), OmniSlugField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.FileField()), OmniFileField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.ImageField()), OmniImageField)
        self.assertEqual(OmniField.get_concrete_class_for_model_field(models.DurationField()), OmniDurationField)
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.GenericIPAddressField()),
            OmniGenericIPAddressField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.CommaSeparatedIntegerField()),
            OmniCharField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.PositiveSmallIntegerField()),
            OmniIntegerField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ForeignKey(DummyModel2)),
            OmniForeignKeyField
        )
        self.assertEqual(
            OmniField.get_concrete_class_for_model_field(models.ManyToManyField(DummyModel2)),
            OmniManyToManyField
        ) 
Example 25
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_field_class(self):
        """
        The model should define the correct field class
        """
        self.assertEqual(OmniCharField.FIELD_CLASS, 'django.forms.CharField') 
Example 26
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_protocol(self):
        """
        The model should have a protocol field
        """
        field = OmniGenericIPAddressField._meta.get_field('protocol')
        self.assertIsInstance(field, models.CharField)
        self.assertTrue(field.blank)
        self.assertFalse(field.null)
        self.assertEqual(field.max_length, 4)
        self.assertEqual(field.choices, OmniGenericIPAddressField.PROTOCOL_CHOICES)
        self.assertEqual(field.default, OmniGenericIPAddressField.PROTOCOL_BOTH) 
Example 27
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_subject_field(self):
        """
        The model should define a subject field
        """
        field = OmniFormEmailHandler._meta.get_field('subject')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 28
Project: omni-forms   Author: omni-digital   File: test_models.py    MIT License 5 votes vote down vote up
def test_subject_field(self):
        """
        The model should have a subject field
        """
        field = OmniFormEmailConfirmationHandler._meta.get_field('subject')
        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.max_length, 255)
        self.assertFalse(field.blank)
        self.assertFalse(field.null) 
Example 29
Project: django-echoices   Author: mbourqui   File: tests.py    GNU General Public License v3.0 5 votes vote down vote up
def test_make_echoicefield(self):
        choice = make_echoicefield(ETestStrChoices)
        self.assertTrue(choice.__class__.__bases__[0] is models.CharField)
        self.assertIs(choice.get_internal_type(), models.CharField.__name__) 
Example 30
Project: django-echoices   Author: mbourqui   File: fields.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, echoices, *args, order=None, **kwargs):
        self.echoices = echoices
        self.order = order
        kwargs['choices'] = self._get_sorted_choices()
        default = kwargs.get('default')
        if default:
            if not isinstance(default, self.echoices):
                raise AttributeError(
                    "Illegal default value: {}. Must be an instance of {}".format(default, self.echoices))
            kwargs['default'] = default.value
        # Parameters specific to some fields
        if issubclass(self.__class__, models.CharField):
            kwargs['max_length'] = echoices.max_value_length()
        super(self.__class__, self).__init__(*args, **kwargs) 
Example 31
Project: django-echoices   Author: mbourqui   File: fields.py    GNU General Public License v3.0 5 votes vote down vote up
def deconstruct(self):
        name, path, args, kwargs = super(self.__class__, self).deconstruct()
        # Drop the parameters set by our field
        del kwargs['choices']
        if issubclass(self.__class__, models.CharField):
            del kwargs['max_length']
        # Set the parameters in our non-trivial formats
        kwargs['echoices'] = self.echoices
        if self.has_default():
            kwargs['default'] = self.get_default()
        return name, path, args, kwargs 
Example 32
Project: tri.form   Author: TriOptima   File: test_compat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_defaults_factory():
    from django.db import models
    base = dict(parse_empty_string_as_none=True, required=True, display_name=None)

    assert field_defaults_factory(models.CharField(null=False, blank=False)) == merged(base, dict(parse_empty_string_as_none=False))
    assert field_defaults_factory(models.CharField(null=False, blank=True)) == merged(base, dict(parse_empty_string_as_none=False, required=False))

    assert field_defaults_factory(models.CharField(null=True, blank=False)) == merged(base, dict(required=False))
    assert field_defaults_factory(models.CharField(null=True, blank=True)) == merged(base, dict(required=False)) 
Example 33
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_from_model_blank_handling():
    from tests.models import Foo

    from django.db.models import CharField

    subject = Field.from_model(model=Foo, model_field=CharField(null=True, blank=False))
    assert True is subject.parse_empty_string_as_none

    subject = Field.from_model(model=Foo, model_field=CharField(null=False, blank=True))
    assert False is subject.parse_empty_string_as_none 
Example 34
Project: tri.form   Author: TriOptima   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_name_field(field):
    from django.db import models
    fields = [x.attname for x in get_fields(field.model_field.target_field.model) if isinstance(x, models.CharField)]
    if 'name' in fields:
        return 'name'
    else:
        name_fields = [x for x in fields if 'name' in x]
        if name_fields:
            return name_fields[0]

    assert fields, "Searching for a field requires it to have a character field we can use for searching. I couldn't find one to use as a guess you you must specify how to perform the search explicitly via `extra__endpoint_attrs`"
    return fields[0] 
Example 35
Project: openhatch   Author: campbe13   File: 0006_rename_rel_to_project_exp.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Link_ProjectExp_Tag'
        db.create_table('profile_link_projectexp_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('project_exp', models.ForeignKey(orm.ProjectExp)),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 4, 847921))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_ProjectExp_Tag'])
        
        # Adding model 'ProjectExp'
        db.create_table('profile_projectexp', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.Person)),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person_role', models.CharField(max_length=200)),
            ('tags', models.TextField()),
            ('time_record_was_created', models.DateTimeField()),
            ('url', models.URLField(max_length=200)),
            ('description', models.TextField()),
            ('time_start', models.DateTimeField()),
            ('time_finish', models.DateTimeField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('source', models.CharField(max_length=100)),
        ))
        db.send_create_signal('profile', ['ProjectExp'])
        
        # Deleting model 'link_persontoprojectrelationship_tag'
        db.delete_table('profile_link_persontoprojectrelationship_tag')
        
        # Deleting model 'persontoprojectrelationship'
        db.delete_table('profile_persontoprojectrelationship')
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 9, 4, 301717))) 
Example 36
Project: openhatch   Author: campbe13   File: 0006_rename_rel_to_project_exp.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Deleting model 'Link_ProjectExp_Tag'
        db.delete_table('profile_link_projectexp_tag')
        
        # Deleting model 'ProjectExp'
        db.delete_table('profile_projectexp')
        
        # Adding model 'link_persontoprojectrelationship_tag'
        db.create_table('profile_link_persontoprojectrelationship_tag', (
            ('person_to_project_relationship', models.ForeignKey(orm['profile.PersonToProjectRelationship'])),
            ('source', models.CharField(max_length=200)),
            ('tag', models.ForeignKey(orm['profile.Tag'])),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 149232))),
            ('id', models.AutoField(primary_key=True)),
        ))
        db.send_create_signal('profile', ['link_persontoprojectrelationship_tag'])
        
        # Adding model 'persontoprojectrelationship'
        db.create_table('profile_persontoprojectrelationship', (
            ('description', models.TextField()),
            ('tags', models.TextField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('id', models.AutoField(primary_key=True)),
            ('time_start', models.DateTimeField()),
            ('source', models.CharField(max_length=100)),
            ('url', models.URLField(max_length=200)),
            ('time_record_was_created', models.DateTimeField()),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person', models.ForeignKey(orm['profile.Person'])),
            ('time_finish', models.DateTimeField()),
            ('person_role', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['persontoprojectrelationship'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 569217))) 
Example 37
Project: openhatch   Author: campbe13   File: 0001_initial.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'Person'
        db.create_table('profile_person', (
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
            ('username', models.CharField(max_length=200)),
            ('password_hash_md5', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Person'])
        
        # Adding model 'PersonToProjectRelationship'
        db.create_table('profile_persontoprojectrelationship', (
            ('id', models.AutoField(primary_key=True)),
            ('person', models.ForeignKey(orm.Person)),
            ('project', models.ForeignKey(orm['search.Project'])),
            ('person_role', models.CharField(max_length=200)),
            ('tags', models.TextField()),
            ('time_record_was_created', models.DateTimeField()),
            ('url', models.URLField(max_length=200)),
            ('description', models.TextField()),
            ('time_start', models.DateTimeField()),
            ('time_finish', models.DateTimeField()),
            ('man_months', models.PositiveIntegerField()),
            ('primary_language', models.CharField(max_length=200)),
            ('source', models.CharField(max_length=100)),
        ))
        db.send_create_signal('profile', ['PersonToProjectRelationship']) 
Example 38
Project: openhatch   Author: campbe13   File: 0005_add_tag_tagtypes_linkp2prel_to_tag.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Adding model 'TagTypes'
        db.create_table('profile_tagtypes', (
            ('id', models.AutoField(primary_key=True)),
            ('prefix', models.CharField(max_length=20)),
        ))
        db.send_create_signal('profile', ['TagTypes'])
        
        # Adding model 'Link_PersonToProjectRelationship_Tag'
        db.create_table('profile_link_persontoprojectrelationship_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('tag', models.ForeignKey(orm.Tag)),
            ('person_to_project_relationship', models.ForeignKey(orm.PersonToProjectRelationship)),
            ('time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 1, 54833))),
            ('source', models.CharField(max_length=200)),
        ))
        db.send_create_signal('profile', ['Link_PersonToProjectRelationship_Tag'])
        
        # Adding model 'Tag'
        db.create_table('profile_tag', (
            ('id', models.AutoField(primary_key=True)),
            ('text', models.CharField(max_length=50)),
            ('type', models.CharField(max_length=50)),
        ))
        db.send_create_signal('profile', ['Tag'])
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 5, 0, 489277))) 
Example 39
Project: openhatch   Author: campbe13   File: 0006_add_fields_to_bug.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def forwards(self, orm):
        
        # Changing field 'Project.name'
        db.alter_column('search_project', 'name', models.CharField(unique=True, max_length=200)) 
Example 40
Project: openhatch   Author: campbe13   File: 0006_add_fields_to_bug.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def backwards(self, orm):
        
        # Changing field 'Project.name'
        db.alter_column('search_project', 'name', models.CharField(max_length=200)) 
Example 41
Project: chattR   Author: patrickstocklin   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30)) 
Example 42
Project: opadmin   Author: cc0411   File: filters.py    GNU General Public License v3.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 43
Project: StormOnline   Author: stormsha   File: filters.py    Apache License 2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (
                isinstance(field, models.CharField)
                and field.max_length > 20
                or isinstance(field, models.TextField)
               ) 
Example 44
Project: litmus-site   Author: alps-jbnu   File: problem.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def add_i18n_name(self, language):
        queryset = self._clone()
        alias = unique_together_left_join(queryset, ProblemTranslation, 'problem', 'language', language)
        return queryset.annotate(i18n_name=Coalesce(RawSQL('%s.name' % alias, ()), F('name'),
                                                    output_field=models.CharField())) 
Example 45
Project: litmus-site   Author: alps-jbnu   File: problem.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def add_problem_i18n_name(self, key, language, name_field=None):
        queryset = self._clone() if name_field is None else self.annotate(_name=F(name_field))
        alias = unique_together_left_join(queryset, ProblemTranslation, 'problem', 'language', language,
                                          parent_model=Problem)
        # You must specify name_field if Problem is not yet joined into the QuerySet.
        kwargs = {key: Coalesce(RawSQL('%s.name' % alias, ()),
                                F(name_field) if name_field else RawSQLColumn(Problem, 'name'),
                                output_field=models.CharField())}
        return queryset.annotate(**kwargs) 
Example 46
Project: aas   Author: Uninett   File: mappings.py    GNU General Public License v3.0 5 votes vote down vote up
def prepare(self, field_name, model_for_field):
        field = model_for_field._meta.get_field(field_name)
        if isinstance(field, (models.CharField, models.TextField)) and not field.null:
            self.none_value = "" 
Example 47
Project: django-idcops   Author: Wenvki   File: list.py    Apache License 2.0 5 votes vote down vote up
def allow_search_fields(self, exclude=None, include=None):
        opts = self.opts

        def construct_search(model):
            exclude = [f.name for f in opts.fields if getattr(f, 'choices')]
            fields = model._meta.fields
            _fields = []
            for f in fields:
                if isinstance(f, models.CharField) and f.name not in exclude:
                    _fields.append(f.name + '__icontains')
            return _fields

        if not exclude:
            exclude = ['onidc', 'slug', 'created', 'modified']
        exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])

        fields = construct_search(self.model)
        for f in opts.fields:
            if exclude and f.name in exclude:
                continue
            if isinstance(f, models.ForeignKey):
                submodel = f.related_model
                for sub in submodel._meta.fields:
                    if exclude and sub.name in exclude:
                        continue
                    if isinstance(
                            sub, models.CharField) and not getattr(
                            sub, 'choices'):
                        fields.append(f.name + '__' + sub.name + '__icontains')
            if isinstance(f, (models.CharField, models.TextField)):
                fields.append(f.name + '__icontains')
        return fields 
Example 48
Project: django-idcops   Author: Wenvki   File: utils.py    Apache License 2.0 5 votes vote down vote up
def nature_field_name(model):
    """ Return model CharField , SlugField Field name use nature field."""
    opts = model._meta
    fields = [
        f.name for f in opts.fields if (
            isinstance(f, models.CharField)
            and not getattr(f, 'blank', False)
        )
    ]
    if fields:
        if 'name' in fields:
            return 'name'
        elif 'text' in fields:
            return 'text'
        elif 'title' in fields:
            return 'title'
        elif 'username' in fields:
            return 'username'
        elif 'linenum' in fields:
            return 'linenum'
        elif 'kcnum' in fields:
            return 'kcnum'
        else:
            if 'created' in [f.name for f in opts.fields]:
                return 'created'
            else:
                return fields[0]
    else:
        if 'created' in [f.name for f in opts.get_fields()]:
            return 'created'
        else:
            return '{}'.format(opts.pk.attname) 
Example 49
Project: django-idcops   Author: Wenvki   File: tasks.py    Apache License 2.0 5 votes vote down vote up
def get_related_client_name(obj):
    related_clients = []
    for f in obj._meta.fields:
        if f.related_model is Client or (
                f.name == 'client' and isinstance(f, models.CharField)):
            value = display_for_field(f.value_from_object(obj), f, html=False)
            related_clients.append(value)
    return '{}'.format(", ".join(c for c in list(set(related_clients)))) 
Example 50
Project: TESTGIT   Author: B-ROY   File: validation.py    Apache License 2.0 5 votes vote down vote up
def validate_field(self, errors, opts, f):
        """
        MySQL has the following field length restriction:
        No character (varchar) fields can have a length exceeding 255
        characters if they have a unique index on them.
        """
        from django.db import models
        varchar_fields = (models.CharField, models.CommaSeparatedIntegerField,
                models.SlugField)
        if (isinstance(f, varchar_fields) and f.unique
                and (f.max_length is None or int(f.max_length) > 255)):
            msg = '"%(name)s": %(cls)s cannot have a "max_length" greater than 255 when using "unique=True".'
            errors.add(opts, msg % {'name': f.name, 'cls': f.__class__.__name__}) 
Example 51
Project: AneMo   Author: jspargo   File: test_operations.py    GNU General Public License v2.0 5 votes vote down vote up
def set_up_test_model(self):
        operations = [migrations.CreateModel(
            "Neighborhood",
            [
                ("id", models.AutoField(primary_key=True)),
                ('name', models.CharField(max_length=100, unique=True)),
                ('geom', fields.MultiPolygonField(srid=4326)),
            ],
        )]
        return self.apply_operations('gis', ProjectState(), operations) 
Example 52
Project: django-angularjs-blog   Author: bluedazzle   File: test_Serializer.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        self.time_func = TimeFormatFactory.get_time_func('string')
        # DATABASES = {
        #     'default': {
        #     'ENGINE': 'django.db.backends.sqlite3',
        #     'NAME': ':memory:',
        #     'USER': '',                      # Not used with sqlite3.
        #     'PASSWORD': '',                  # Not used with sqlite3.
        #     'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        #     'PORT': '',
        #     }
        # }
        # settings.configure(DATABASES=DATABASES, DEBUG=True)
        # class TestAuthor(models.Model):
        #     name = models.CharField(default='test_author')
        #
        #     def __unicode__(self):
        #         return self.name
        #
        # class TestTags(models.Model):
        #     tag = models.CharField(default='test_tag')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        # class TestArticle(models.Model):
        #     title = models.CharField(default='test')
        #     content = models.CharField(default='test')
        #     author = models.ForeignKey(TestAuthor, related_name='author_art')
        #     tags = models.ManyToManyField(TestTags, related_name='tag_art')
        #     create_time = models.DateTimeField(auto_now=True)
        #
        #
        # self.author = TestAuthor()
        # self.author.save()
        # tags = TestTags(tag='tag1')
        # tags.save()
        # self.article = TestArticle(author=self.author)
        # self.article.tags.add(tags)
        # self.article.save() 
Example 53
Project: GTDWeb   Author: lanbing510   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def add_spatial_version_related_fields(sender, **kwargs):
    """
    Adds fields after establishing a database connection to prevent database
    operations at compile time.
    """
    if connection_created.disconnect(add_spatial_version_related_fields, sender=DatabaseWrapper):
        spatial_version = connection.ops.spatial_version[0]
        if spatial_version >= 4:
            SpatialiteSpatialRefSys.add_to_class('srtext', models.CharField(max_length=2048))
            SpatialiteGeometryColumns.add_to_class('type', models.IntegerField(db_column='geometry_type'))
        else:
            SpatialiteGeometryColumns.add_to_class('type', models.CharField(max_length=30)) 
Example 54
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_field_checks(self):
        class BadField(models.Model):
            field = encrypt(models.CharField())

            class Meta:
                app_label = 'myapp'

        model = BadField()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        # The inner CharField is missing a max_length.
        self.assertEqual('fields.E120', errors[0].id)
        self.assertIn('max_length', errors[0].msg) 
Example 55
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_deconstruct_args(self):
        field = encrypt(models.CharField(max_length=20))
        name, path, args, kwargs = field.deconstruct()
        new = encrypt(*args, **kwargs)
        self.assertEqual(new.max_length, field.max_length) 
Example 56
Project: django-cryptography   Author: georgemarshall   File: test_encrypted.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_model_field_formfield(self):
        model_field = encrypt(models.CharField(max_length=27))
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, forms.CharField)
        self.assertEqual(form_field.max_length, 27) 
Example 57
Project: kerrokantasi   Author: City-of-Helsinki   File: base.py    MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        pk_type = self._meta.pk.get_internal_type()
        if pk_type == 'CharField':
            if not self.pk:
                self.pk = generate_id()
        elif pk_type == 'AutoField':
            pass
        else:  # pragma: no cover
            raise Exception('Unsupported primary key field: %s' % pk_type)
        if not kwargs.pop("no_modified_at_update", False):
            # Useful for importing, etc.
            self.modified_at = timezone.now()
        super().save(*args, **kwargs) 
Example 58
Project: dingtalk-django-example   Author: 007gzs   File: model.py    GNU General Public License v3.0 5 votes vote down vote up
def ex_search_fields(cls):
        ret = set()
        for field in cls._meta.fields:
            if not field.db_index and not field.unique \
                    and field.name == 'name' and isinstance(field, models.CharField):
                ret.add(field.name)
        return ret 
Example 59
Project: aswan   Author: momosecurity   File: models.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def get_hit_log_model(db_table):
    class CustomMetaClass(ModelBase):
        def __new__(cls, name, bases, attrs):
            model = super(CustomMetaClass, cls).__new__(cls, name, bases,
                                                        attrs)
            model._meta.db_table = db_table
            model._meta.index_together = (
                ('time',),
                ('user_id',),
            )
            model.managed = False
            return model

    class HitLogModel(models.Model, metaclass=CustomMetaClass):
        time = models.DateTimeField(verbose_name=_(u'命中时间'))
        rule_id = models.IntegerField(verbose_name=_(u'规则ID'))
        user_id = models.IntegerField(verbose_name=_(u'命中用户'))
        kwargs = models.CharField(max_length=128, null=False, default='', verbose_name=_(u'扩展参数'))
        req_body = models.CharField(max_length=512, null=False, default='', verbose_name=_(u'请求参数'))
        control = models.CharField(max_length=16, null=False, default='', verbose_name=_(u'管控原子'))
        custom = models.CharField(max_length=50, null=False, default='', verbose_name=_(u'策略组解释'))
        group_name = models.CharField(max_length=256, null=False, default='',
                                      verbose_name=_(u'策略原子组名称'))
        group_uuid = models.CharField(max_length=36, null=False, default='',
                                      verbose_name=_(u'策略原子组UUID'))
        hit_number = models.PositiveSmallIntegerField(null=False, default=1, verbose_name=_(u'命中次序'))

        objects = Manager()

    return HitLogModel 
Example 60
Project: scope   Author: CCA-Public   File: models.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_users(cls, query=None, sort_field="username"):
        """Get users based on a query string.

        Querying over 'username', 'first_name', 'last_name', 'email' and a
        concatenation of related group names separated by ', '. The group name
        concatenation can be used to sort and display in the 'group_names' field
        and the output will be the same as the equally called function from this
        model. The resulting users will be ordered by a given 'sort_field'. Returns
        all users if no query is given and sorts by 'username' by default.
        """

        class GroupsSQ(models.Subquery):
            """Subquery to concatenate group names, requires MySQL or SQLite"""

            template = "(SELECT GROUP_CONCAT(name, ', ') FROM (%(subquery)s))"
            output_field = models.CharField()

        subquery = GroupsSQ(Group.objects.filter(user=models.OuterRef("pk")))
        users = cls.objects.annotate(group_names=subquery).order_by(sort_field)
        if not query:
            return users.all()
        return users.filter(
            models.Q(username__icontains=query)
            | models.Q(first_name__icontains=query)
            | models.Q(last_name__icontains=query)
            | models.Q(email__icontains=query)
            | models.Q(group_names__icontains=query)
        ) 
Example 61
Project: koku   Author: project-koku   File: helpers.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_storage_daily_table(self):
        """Populate the daily table."""
        included_fields = [
            'namespace',
            'pod',
            'persistentvolumeclaim',
            'persistentvolume',
            'storageclass',
            'persistentvolume_labels',
            'persistentvolumeclaim_labels'
        ]
        annotations = {
            'node': Value(random.choice(self.line_items).get('node'), output_field=CharField()),
            'usage_start': F('report__interval_start'),
            'usage_end': F('report__interval_start'),
            'persistentvolumeclaim_capacity_bytes': Max('persistentvolumeclaim_capacity_bytes'),
            'persistentvolumeclaim_capacity_byte_seconds': Sum('persistentvolumeclaim_capacity_byte_seconds'),
            'volume_request_storage_byte_seconds': Sum('volume_request_storage_byte_seconds'),
            'persistentvolumeclaim_usage_byte_seconds': Sum('persistentvolumeclaim_usage_byte_seconds'),
            'cluster_id': F('report_period__cluster_id'),
            'cluster_alias': Value(self.cluster_alias, output_field=CharField()),
        }
        entries = OCPStorageLineItem.objects\
            .values(*included_fields)\
            .annotate(**annotations)

        for entry in entries:
            entry['total_seconds'] = 3600
            daily = OCPStorageLineItemDaily(**entry)
            daily.save() 
Example 62
Project: koku   Author: project-koku   File: helpers.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_storage_daily_summary_table(self):
        """Populate the daily summary table."""
        included_fields = [
            'usage_start',
            'usage_end',
            'namespace',
            'pod',
            'node',
            'persistentvolumeclaim',
            'persistentvolume',
            'storageclass',
            'cluster_id',
            'cluster_alias'
        ]
        annotations = {
            'volume_labels': Coalesce(F('persistentvolume_labels'), F('persistentvolumeclaim_labels')),
            'persistentvolumeclaim_capacity_gigabyte': ExpressionWrapper(
                F('persistentvolumeclaim_capacity_bytes') * math.pow(2, -30),
                output_field=DecimalField()
            ),
            'persistentvolumeclaim_capacity_gigabyte_months': ExpressionWrapper(
                F('persistentvolumeclaim_capacity_byte_seconds') / 86400 * 30 * math.pow(2, -30),
                output_field=DecimalField()
            ),
            'volume_request_storage_gigabyte_months': ExpressionWrapper(
                F('volume_request_storage_byte_seconds') / 86400 * 30 * math.pow(2, -30),
                output_field=DecimalField()
            ),
            'persistentvolumeclaim_usage_gigabyte_months': ExpressionWrapper(
                F('persistentvolumeclaim_usage_byte_seconds') / 86400 * 30 * math.pow(2, -30),
                output_field=DecimalField()
            ),
            'data_source': Value('Storage', output_field=CharField())
        }

        entries = OCPStorageLineItemDaily.objects.values(*included_fields).annotate(**annotations)

        for entry in entries:
            summary = OCPUsageLineItemDailySummary(**entry)
            summary.save() 
Example 63
Project: OwadeReborn   Author: CarlosLannister   File: models.py    GNU General Public License v3.0 5 votes vote down vote up
def __unicode__(self):
        if self.description != "":
            return "%s (%s)" % (self.name, self.description)
        return "%s" % (self.name)

#class SubCategory(models.Model):
#    name = models.CharField(max_length=32)
#
#    category = models.ForeignKey(Category)
#
#    def __unicode__(self):
#        return "%s" % (self.name) 
Example 64
Project: kobo-predict   Author: awemulya   File: country_field.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_internal_type(self):
        return "CharField" 
Example 65
Project: django-conditioner   Author: omni-digital   File: test_signals.py    MIT License 5 votes vote down vote up
def test_model_signal_field(self):
        """Test model 'signal' field"""
        field = self.model._meta.get_field('signal')

        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.verbose_name, 'signal')
        self.assertEqual(field.choices, self.model.SIGNAL_CHOICES)
        self.assertEqual(field.max_length, 64) 
Example 66
Project: django-conditioner   Author: omni-digital   File: test_misc.py    MIT License 5 votes vote down vote up
def test_model_level_field(self):
        """Test model 'level' field"""
        field = self.model._meta.get_field('level')

        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.verbose_name, 'logging level')
        self.assertEqual(field.choices, self.model.LEVEL_CHOICES)
        self.assertEqual(field.max_length, 64) 
Example 67
Project: django-conditioner   Author: omni-digital   File: test_common.py    MIT License 5 votes vote down vote up
def test_model_subject_field(self):
        """Test model 'subject' field"""
        field = self.model._meta.get_field('subject')

        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.verbose_name, 'subject')
        self.assertEqual(field.max_length, 256) 
Example 68
Project: django-conditioner   Author: omni-digital   File: test_common.py    MIT License 5 votes vote down vote up
def test_model_template_field(self):
        """Test model 'template' field"""
        field = self.model._meta.get_field('template')

        self.assertIsInstance(field, models.CharField)
        self.assertEqual(field.verbose_name, 'template')
        self.assertEqual(field.max_length, 256) 
Example 69
Project: ops22   Author: spark8103   File: filters.py    MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (isinstance(field, models.CharField) and field.max_length > 20) or isinstance(field, models.TextField) 
Example 70
Project: django-echoices   Author: mbourqui   File: fields.py    GNU General Public License v3.0 4 votes vote down vote up
def make_echoicefield(echoices, *args, klass_name=None, **kwargs):
    """
    Construct a subclass of a derived `models.Field` specific to the type of the `EChoice` values.

    Parameters
    ----------
    echoices : subclass of EChoice
    args
        Passed to the derived `models.Field`
    klass_name : str
        Give a specific name to the returned class.
        By default for Django < 1.9, the name will be 'EChoiceField'.
        By default for Django >= 1.9, the name will be the name of the enum appended with 'Field'.
    kwargs
        Passed to the derived `models.Field`

    Returns
    -------
    EChoiceField
        For Django>=1.9, the exact name of the returned Field is based on the name of the `echoices` with a suffixed
        'Field'. For older Django, the returned name of the class is `EChoiceField`.

    """
    assert issubclass(echoices, EChoice)
    value_type = echoices.__getvaluetype__()
    if value_type is str:
        cls_ = models.CharField
    elif value_type is int:
        cls_ = models.IntegerField
    elif value_type is float:
        cls_ = models.FloatField
    elif value_type is bool:
        cls_ = models.BooleanField
    else:
        raise NotImplementedError("Please open an issue if you wish your value type to be supported: "
                                  "https://github.com/mbourqui/django-echoices/issues/new")
    if klass_name and StrictVersion(django_version()) < StrictVersion('1.9.0'):
        warnings.warn("Django < 1.9 throws an 'ImportError' if the class name is not defined in the module. "
                      "The provided klass_name will be replaced by {}".format(EChoiceField.__name__), RuntimeWarning)
    klass_name = EChoiceField.__name__ if StrictVersion(django_version()) < StrictVersion('1.9.0') else \
        klass_name if klass_name else "{}Field".format(echoices.__name__)
    d = dict(cls_.__dict__)
    d.update(dict(EChoiceField.__dict__))
    return type(klass_name, (cls_,), d)(echoices, *args, **kwargs)

# TODO: MultipleEChoiceField 
Example 71
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_get_name_field():
    from django.db.models import (
        Model,
        IntegerField,
        CharField,
        ForeignKey,
        CASCADE,
    )

    class Foo1(Model):
        a = IntegerField()
        name = CharField(max_length=255)

    class Bar1(Model):
        foo = ForeignKey(Foo1, on_delete=CASCADE)

    class Foo2(Model):
        a = IntegerField()
        fooname = CharField(max_length=255)
        name = CharField(max_length=255)

    class Bar2(Model):
        foo = ForeignKey(Foo2, on_delete=CASCADE)

    class Foo3(Model):
        name = IntegerField()
        fooname = CharField(max_length=255)

    class Bar3(Model):
        foo = ForeignKey(Foo3, on_delete=CASCADE)

    class Foo4(Model):
        fooname = CharField(max_length=255)
        barname = CharField(max_length=255)

    class Bar4(Model):
        foo = ForeignKey(Foo4, on_delete=CASCADE)

    class Foo5(Model):
        blabla = CharField(max_length=255)

    class Bar5(Model):
        foo = ForeignKey(Foo5, on_delete=CASCADE)

    class Foo6(Model):
        a = IntegerField()

    class Bar6(Model):
        foo = ForeignKey(Foo6, on_delete=CASCADE)

    assert get_name_field(Form.from_model(model=Bar1, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar2, data={}).fields_by_name.foo) == 'name'
    assert get_name_field(Form.from_model(model=Bar3, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar4, data={}).fields_by_name.foo) == 'fooname'
    assert get_name_field(Form.from_model(model=Bar5, data={}).fields_by_name.foo) == 'blabla'
    with pytest.raises(AssertionError):
        get_name_field(Form.from_model(model=Bar6, data={}).fields_by_name.foo) 
Example 72
def forwards(self, orm):
        
        # Adding field 'ProjectExp.time_start'
        db.add_column('profile_projectexp', 'time_start', models.DateTimeField(null=True))
        
        # Adding field 'ProjectExp.last_touched'
        db.add_column('profile_projectexp', 'last_touched', models.DateTimeField(null=True))
        
        # Adding field 'Tag.tag_type'
        db.add_column('profile_tag', 'tag_type', models.ForeignKey(orm.TagType, null=True))
        
        # Adding field 'ProjectExp.time_finish'
        db.add_column('profile_projectexp', 'time_finish', models.DateTimeField(null=True))
        
        # Deleting field 'Tag.type'
        db.delete_column('profile_tag', 'type')
        
        # Deleting field 'ProjectExp.tags'
        db.delete_column('profile_projectexp', 'tags')
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 14, 38, 36, 403378)))
        
        # Changing field 'Person.last_touched'
        db.alter_column('profile_person', 'last_touched', models.DateTimeField(null=True))
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 14, 38, 35, 670600)))
        
        # Changing field 'ProjectExp.url'
        db.alter_column('profile_projectexp', 'url', models.URLField(max_length=200, null=True))
        
        # Changing field 'ProjectExp.man_months'
        db.alter_column('profile_projectexp', 'man_months', models.PositiveIntegerField(null=True))
        
        # Changing field 'ProjectExp.source'
        db.alter_column('profile_projectexp', 'source', models.CharField(max_length=100, null=True))
        
        # Changing field 'ProjectExp.primary_language'
        db.alter_column('profile_projectexp', 'primary_language', models.CharField(max_length=200, null=True))
        
        # Changing field 'ProjectExp.time_record_was_created'
        db.alter_column('profile_projectexp', 'time_record_was_created', models.DateTimeField(null=True)) 
Example 73
def backwards(self, orm):
        
        # Deleting field 'ProjectExp.time_start'
        db.delete_column('profile_projectexp', 'time_start')
        
        # Deleting field 'ProjectExp.last_touched'
        db.delete_column('profile_projectexp', 'last_touched')
        
        # Deleting field 'Tag.tag_type'
        db.delete_column('profile_tag', 'tag_type_id')
        
        # Deleting field 'ProjectExp.time_finish'
        db.delete_column('profile_projectexp', 'time_finish')
        
        # Adding field 'Tag.type'
        db.add_column('profile_tag', 'type', models.CharField(max_length=50))
        
        # Adding field 'ProjectExp.tags'
        db.add_column('profile_projectexp', 'tags', models.TextField())
        
        # Changing field 'Link_ProjectExp_Tag.time_record_was_created'
        db.alter_column('profile_link_projectexp_tag', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 50, 22, 475279)))
        
        # Changing field 'Person.last_touched'
        db.alter_column('profile_person', 'last_touched', models.DateTimeField())
        
        # Changing field 'Person.time_record_was_created'
        db.alter_column('profile_person', 'time_record_was_created', models.DateTimeField(default=datetime.datetime(2009, 6, 19, 12, 50, 22, 339421)))
        
        # Changing field 'ProjectExp.url'
        db.alter_column('profile_projectexp', 'url', models.URLField(max_length=200))
        
        # Changing field 'ProjectExp.man_months'
        db.alter_column('profile_projectexp', 'man_months', models.PositiveIntegerField())
        
        # Changing field 'ProjectExp.source'
        db.alter_column('profile_projectexp', 'source', models.CharField(max_length=100))
        
        # Changing field 'ProjectExp.primary_language'
        db.alter_column('profile_projectexp', 'primary_language', models.CharField(max_length=200))
        
        # Changing field 'ProjectExp.time_record_was_created'
        db.alter_column('profile_projectexp', 'time_record_was_created', models.DateTimeField()) 
Example 74
Project: openhatch   Author: campbe13   File: 0002_milestone_b_data.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def forwards(self, orm):
        
        try:
            # Adding field 'Bug.submitter_realname'
            db.add_column('search_bug', 'submitter_realname', models.CharField(max_length=200))
        except:
            pass

        try:
             # Adding field 'Project.icon_url'
            db.add_column('search_project', 'icon_url', models.URLField(max_length=200))
        except:
            pass
        
        try:
            # Adding field 'Bug.last_touched'
            db.add_column('search_bug', 'last_touched', models.DateField(default=datetime.datetime(1970, 1, 1, 12, 0, 0)))
        except:
            pass
        
        try:
            # Adding field 'Bug.importance'
            db.add_column('search_bug', 'importance', models.CharField(max_length=200))
        except:
            pass
        
        try:
            # Adding field 'Bug.people_involved'
            db.add_column('search_bug', 'people_involved', models.IntegerField(default=0))
        except:
            pass
        
        try:
            # Adding field 'Bug.last_polled'
            db.add_column('search_bug', 'last_polled', models.DateField(default=datetime.datetime(1970, 1, 1, 12, 0, 0)))
        except:
            pass
        
        try:
            # Adding field 'Bug.submitter_username'
            db.add_column('search_bug', 'submitter_username', models.CharField(max_length=200))
        except:
            pass 
Example 75
Project: chattR   Author: patrickstocklin   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 76
Project: TESTGIT   Author: B-ROY   File: layermapping.py    Apache License 2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
            isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
                if model_field.max_length and len(val) > model_field.max_length:
                    raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                        (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2] # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' %
                                     (model_field.max_digits, model_field.decimal_places, max_prec))
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 77
Project: AneMo   Author: jspargo   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
                if model_field.max_length and len(val) > model_field.max_length:
                    raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                        (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal('A DecimalField with max_digits %d, decimal_places %d must round to an absolute value less than 10^%d.' %
                                     (model_field.max_digits, model_field.decimal_places, max_prec))
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 78
Project: GTDWeb   Author: lanbing510   File: layermapping.py    GNU General Public License v2.0 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 79
Project: liberator   Author: libscie   File: layermapping.py    Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def verify_ogr_field(self, ogr_field, model_field):
        """
        Verifies if the OGR Field contents are acceptable to the Django
        model field.  If they are, the verified value is returned,
        otherwise the proper exception is raised.
        """
        if (isinstance(ogr_field, OFTString) and
                isinstance(model_field, (models.CharField, models.TextField))):
            if self.encoding:
                # The encoding for OGR data sources may be specified here
                # (e.g., 'cp437' for Census Bureau boundary files).
                val = force_text(ogr_field.value, self.encoding)
            else:
                val = ogr_field.value
            if model_field.max_length and len(val) > model_field.max_length:
                raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
                                    (model_field.name, model_field.max_length, len(val)))
        elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
            try:
                # Creating an instance of the Decimal value to use.
                d = Decimal(str(ogr_field.value))
            except DecimalInvalidOperation:
                raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)

            # Getting the decimal value as a tuple.
            dtup = d.as_tuple()
            digits = dtup[1]
            d_idx = dtup[2]  # index where the decimal is

            # Maximum amount of precision, or digits to the left of the decimal.
            max_prec = model_field.max_digits - model_field.decimal_places

            # Getting the digits to the left of the decimal place for the
            # given decimal.
            if d_idx < 0:
                n_prec = len(digits[:d_idx])
            else:
                n_prec = len(digits) + d_idx

            # If we have more than the maximum digits allowed, then throw an
            # InvalidDecimal exception.
            if n_prec > max_prec:
                raise InvalidDecimal(
                    'A DecimalField with max_digits %d, decimal_places %d must '
                    'round to an absolute value less than 10^%d.' %
                    (model_field.max_digits, model_field.decimal_places, max_prec)
                )
            val = d
        elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
            # Attempt to convert any OFTReal and OFTString value to an OFTInteger.
            try:
                val = int(ogr_field.value)
            except ValueError:
                raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
        else:
            val = ogr_field.value
        return val 
Example 80
Project: koku   Author: project-koku   File: helpers.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def _populate_daily_table(self):
        """Populate the daily table."""
        OCPUsageLineItemDaily.objects.all().delete()
        included_fields = [
            'namespace',
            'pod',
            'node',
            'pod_labels',
            'resource_id',
        ]
        annotations = {
            'usage_start': F('report__interval_start'),
            'usage_end': F('report__interval_start'),
            'pod_usage_cpu_core_seconds': Sum('pod_usage_cpu_core_seconds'),
            'pod_request_cpu_core_seconds': Sum('pod_request_cpu_core_seconds'),
            'pod_limit_cpu_core_seconds': Sum('pod_limit_cpu_core_seconds'),
            'pod_usage_memory_byte_seconds': Sum('pod_usage_memory_byte_seconds'),
            'pod_request_memory_byte_seconds': Sum('pod_request_memory_byte_seconds'),
            'pod_limit_memory_byte_seconds': Sum('pod_limit_memory_byte_seconds'),
            'cluster_id': F('report_period__cluster_id'),
            'cluster_alias': Value(self.cluster_alias, output_field=CharField()),
            'node_capacity_cpu_cores': Max('node_capacity_cpu_cores'),
            'node_capacity_cpu_core_seconds': Max('node_capacity_cpu_core_seconds'),
            'node_capacity_memory_bytes': Max('node_capacity_memory_bytes'),
            'node_capacity_memory_byte_seconds': Max('node_capacity_memory_byte_seconds')
        }
        entries = OCPUsageLineItem.objects\
            .values(*included_fields)\
            .annotate(**annotations)

        cluster_capacity_cpu_core_seconds = Decimal(0)
        cluster_capacity_memory_byte_seconds = Decimal(0)

        cluster_cap = OCPUsageLineItem.objects\
            .values(*['node'])\
            .annotate(
                **{
                    'node_capacity_cpu_core_seconds': Max('node_capacity_cpu_core_seconds'),
                    'node_capacity_memory_byte_seconds': Sum('node_capacity_memory_byte_seconds')
                }
            )

        for node in cluster_cap:
            cluster_capacity_cpu_core_seconds += node.get('node_capacity_cpu_core_seconds')
            cluster_capacity_memory_byte_seconds += node.get('node_capacity_memory_byte_seconds')

        for entry in entries:
            entry['total_seconds'] = 3600
            entry['cluster_capacity_cpu_core_seconds'] = cluster_capacity_cpu_core_seconds
            entry['cluster_capacity_memory_byte_seconds'] = cluster_capacity_memory_byte_seconds
            entry['total_capacity_cpu_core_seconds'] = cluster_capacity_cpu_core_seconds
            entry['total_capacity_memory_byte_seconds'] = cluster_capacity_memory_byte_seconds
            daily = OCPUsageLineItemDaily(**entry)
            daily.save()