Python django.db.models.UUIDField() Examples

The following are 24 code examples of django.db.models.UUIDField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: utils.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def url_str_to_user_pk(s):
    User = get_user_model()
    # TODO: Ugh, isn't there a cleaner way to determine whether or not
    # the PK is a str-like field?
    if getattr(User._meta.pk, 'rel', None):
        pk_field = User._meta.pk.rel.to._meta.pk
    else:
        pk_field = User._meta.pk
    if (hasattr(models, 'UUIDField') and issubclass(
            type(pk_field), models.UUIDField)):
        return s
    try:
        pk_field.to_python('a')
        pk = s
    except ValidationError:
        pk = base36_to_int(s)
    return pk 
Example #2
Source File: test_writer.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_serialize_uuid(self):
        self.assertSerializedEqual(uuid.uuid1())
        self.assertSerializedEqual(uuid.uuid4())

        uuid_a = uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')
        uuid_b = uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')
        self.assertSerializedResultEqual(
            uuid_a,
            ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')", {'import uuid'})
        )
        self.assertSerializedResultEqual(
            uuid_b,
            ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')", {'import uuid'})
        )

        field = models.UUIDField(choices=((uuid_a, 'UUID A'), (uuid_b, 'UUID B')), default=uuid_a)
        string = MigrationWriter.serialize(field)[0]
        self.assertEqual(
            string,
            "models.UUIDField(choices=["
            "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), "
            "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], "
            "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))"
        ) 
Example #3
Source File: test_writer.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_serialize_uuid(self):
        self.assertSerializedEqual(uuid.uuid1())
        self.assertSerializedEqual(uuid.uuid4())

        uuid_a = uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')
        uuid_b = uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')
        self.assertSerializedResultEqual(
            uuid_a,
            ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')", {'import uuid'})
        )
        self.assertSerializedResultEqual(
            uuid_b,
            ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')", {'import uuid'})
        )

        field = models.UUIDField(choices=((uuid_a, 'UUID A'), (uuid_b, 'UUID B')), default=uuid_a)
        string = MigrationWriter.serialize(field)[0]
        self.assertEqual(
            string,
            "models.UUIDField(choices=["
            "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), "
            "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], "
            "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))"
        ) 
Example #4
Source File: test_writer.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_serialize_uuid(self):
        self.assertSerializedEqual(uuid.uuid1())
        self.assertSerializedEqual(uuid.uuid4())

        uuid_a = uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')
        uuid_b = uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')
        self.assertSerializedResultEqual(
            uuid_a,
            ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')", {'import uuid'})
        )
        self.assertSerializedResultEqual(
            uuid_b,
            ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')", {'import uuid'})
        )

        field = models.UUIDField(choices=((uuid_a, 'UUID A'), (uuid_b, 'UUID B')), default=uuid_a)
        string = MigrationWriter.serialize(field)[0]
        self.assertEqual(
            string,
            "models.UUIDField(choices=["
            "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), "
            "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], "
            "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))"
        ) 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_label_and_url_for_value_invalid_uuid(self):
        field = Bee._meta.get_field('honeycomb')
        self.assertIsInstance(field.target_field, UUIDField)
        widget = widgets.ForeignKeyRawIdWidget(field.remote_field, admin.site)
        self.assertEqual(widget.label_and_url_for_value('invalid-uuid'), ('', '')) 
Example #6
Source File: test_process_with_django.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def define_projection_record_class(self):
        class ProjectionRecord(models.Model):
            uid = models.BigAutoField(primary_key=True)

            # Sequence ID (e.g. an entity or aggregate ID).
            projection_id = models.UUIDField()

            # State of the item (serialized dict, possibly encrypted).
            state = models.TextField()

            class Meta:
                db_table = "projections"
                app_label = "projections"
                managed = False

        self.projection_record_class = ProjectionRecord 
Example #7
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deconstruct(self):
        field = models.UUIDField()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(kwargs, {}) 
Example #8
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_uuid_instance_ok(self):
        field = models.UUIDField()
        field.clean(uuid.uuid4(), None)  # no error 
Example #9
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_uuid(self):
        field = models.UUIDField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('550e8400', None)
        self.assertEqual(cm.exception.code, 'invalid')
        self.assertEqual(cm.exception.message % cm.exception.params, "'550e8400' is not a valid UUID.") 
Example #10
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_to_python_int_too_large(self):
        # Fails for integers larger than 128 bits.
        with self.assertRaises(exceptions.ValidationError):
            models.UUIDField().to_python(2 ** 128) 
Example #11
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_to_python_int_values(self):
        self.assertEqual(
            models.UUIDField().to_python(0),
            uuid.UUID('00000000-0000-0000-0000-000000000000')
        )
        # Works for integers less than 128 bits.
        self.assertEqual(
            models.UUIDField().to_python((2 ** 128) - 1),
            uuid.UUID('ffffffff-ffff-ffff-ffff-ffffffffffff')
        ) 
Example #12
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deconstruct(self):
        field = models.UUIDField()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(kwargs, {}) 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_UUIDField_using_Value(self):
        UUID.objects.create()
        UUID.objects.update(uuid=Value(uuid.UUID('12345678901234567890123456789012'), output_field=UUIDField()))
        self.assertEqual(UUID.objects.get().uuid, uuid.UUID('12345678901234567890123456789012')) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_uuid(self):
        CaseTestModel.objects.update(
            uuid=Case(
                # fails on sqlite if output_field is not set explicitly on all
                # Values containing UUIDs
                When(integer=1, then=Value(
                    UUID('11111111111111111111111111111111'),
                    output_field=models.UUIDField(),
                )),
                When(integer=2, then=Value(
                    UUID('22222222222222222222222222222222'),
                    output_field=models.UUIDField(),
                )),
            ),
        )
        self.assertQuerysetEqual(
            CaseTestModel.objects.all().order_by('pk'),
            [
                (1, UUID('11111111111111111111111111111111')),
                (2, UUID('22222222222222222222222222222222')),
                (3, None),
                (2, UUID('22222222222222222222222222222222')),
                (3, None),
                (3, None),
                (4, None),
            ],
            transform=attrgetter('integer', 'uuid')
        ) 
Example #15
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_uuid(self):
        field = models.UUIDField()
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean('550e8400', None)
        self.assertEqual(cm.exception.code, 'invalid')
        self.assertEqual(cm.exception.message % cm.exception.params, "'550e8400' is not a valid UUID.") 
Example #16
Source File: test_uuid.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_to_python(self):
        self.assertIsNone(models.UUIDField().to_python(None)) 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_UUIDField_using_Value(self):
        UUID.objects.create()
        UUID.objects.update(uuid=Value(uuid.UUID('12345678901234567890123456789012'), output_field=UUIDField()))
        self.assertEqual(UUID.objects.get().uuid, uuid.UUID('12345678901234567890123456789012')) 
Example #18
Source File: inspectors.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_pk_description(model, model_field):
    if isinstance(model_field, models.AutoField):
        value_type = _('unique integer value')
    elif isinstance(model_field, models.UUIDField):
        value_type = _('UUID string')
    else:
        value_type = _('unique value')

    return _('A {value_type} identifying this {name}.').format(
        value_type=value_type,
        name=model._meta.verbose_name,
    ) 
Example #19
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_update_uuid(self):
        CaseTestModel.objects.update(
            uuid=Case(
                # fails on sqlite if output_field is not set explicitly on all
                # Values containing UUIDs
                When(integer=1, then=Value(
                    UUID('11111111111111111111111111111111'),
                    output_field=models.UUIDField(),
                )),
                When(integer=2, then=Value(
                    UUID('22222222222222222222222222222222'),
                    output_field=models.UUIDField(),
                )),
            ),
        )
        self.assertQuerysetEqual(
            CaseTestModel.objects.all().order_by('pk'),
            [
                (1, UUID('11111111111111111111111111111111')),
                (2, UUID('22222222222222222222222222222222')),
                (3, None),
                (2, UUID('22222222222222222222222222222222')),
                (3, None),
                (3, None),
                (4, None),
            ],
            transform=attrgetter('integer', 'uuid')
        ) 
Example #20
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_update_UUIDField_using_Value(self):
        UUID.objects.create()
        UUID.objects.update(uuid=Value(uuid.UUID('12345678901234567890123456789012'), output_field=UUIDField()))
        self.assertEqual(UUID.objects.get().uuid, uuid.UUID('12345678901234567890123456789012')) 
Example #21
Source File: test_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def test_should_uuid_convert_id():
    assert_conversion(models.UUIDField, graphene.UUID) 
Example #22
Source File: schema.py    From djangoql with MIT License 5 votes vote down vote up
def get_field_cls(self, field):
        str_fields = (models.CharField, models.TextField, models.UUIDField)
        if isinstance(field, str_fields):
            return StrField
        elif isinstance(field, (models.AutoField, models.IntegerField)):
            return IntField
        elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
            return BoolField
        elif isinstance(field, (models.DecimalField, models.FloatField)):
            return FloatField
        elif isinstance(field, models.DateTimeField):
            return DateTimeField
        elif isinstance(field, models.DateField):
            return DateField
        return DjangoQLField 
Example #23
Source File: utils.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def user_pk_to_url_str(user):
    """
    This should return a string.
    """
    User = get_user_model()
    if (hasattr(models, 'UUIDField') and issubclass(
            type(User._meta.pk), models.UUIDField)):
        if isinstance(user.pk, six.string_types):
            return user.pk
        return user.pk.hex

    ret = user.pk
    if isinstance(ret, six.integer_types):
        ret = int_to_base36(user.pk)
    return str(ret) 
Example #24
Source File: db_compat.py    From tri.table with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def setup_db_compat_django():
    from tri_table import register_column_factory
    try:
        # noinspection PyUnresolvedReferences
        from django.db.models import IntegerField, FloatField, TextField, BooleanField, AutoField, CharField, DateField, DateTimeField, DecimalField, EmailField, TimeField, ForeignKey, ManyToOneRel, ManyToManyField, ManyToManyRel, UUIDField
    except ImportError:
        pass
    else:
        # The order here is significant because of inheritance structure. More specific must be below less specific.

        register_column_factory(CharField, Shortcut(call_target__attribute='text'))
        register_column_factory(UUIDField, Shortcut(call_target__attribute='text'))
        register_column_factory(TimeField, Shortcut(call_target__attribute='time'))
        register_column_factory(EmailField, Shortcut(call_target__attribute='email'))
        register_column_factory(DecimalField, Shortcut(call_target__attribute='decimal'))
        register_column_factory(DateField, Shortcut(call_target__attribute='date'))
        register_column_factory(DateTimeField, Shortcut(call_target__attribute='datetime'))
        register_column_factory(BooleanField, Shortcut(call_target__attribute='boolean'))
        register_column_factory(TextField, Shortcut(call_target__attribute='text'))
        register_column_factory(FloatField, Shortcut(call_target__attribute='float'))
        register_column_factory(IntegerField, Shortcut(call_target__attribute='integer'))
        register_column_factory(AutoField, Shortcut(call_target__attribute='integer', show=False))
        register_column_factory(ManyToOneRel, None)
        register_column_factory(ManyToManyField, Shortcut(call_target__attribute='many_to_many'))
        register_column_factory(ManyToManyRel, None)

        register_column_factory(ForeignKey, Shortcut(call_target__attribute='foreign_key'))