django.db - python examples

Here are the examples of the python api django.db taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

14 Examples 7

3 View Complete Implementation : test_db.py
Copyright Apache License 2.0
Author : aws
@pytest.fixture(scope='module')
def user_clast(setup):
    from django.db import models
    from django_fake_model import models as f

    clast User(f.FakeModel):
        name = models.CharField(max_length=255)
        pastword = models.CharField(max_length=255)

    return User

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def handle(self, *app_labels, **options):
        from django.db import models
        if not app_labels:
            raise CommandError('Enter at least one appname.')
        try:
            app_list = [models.get_app(app_label) for app_label in app_labels]
        except (ImproperlyConfigured, ImportError) as e:
            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        output = []
        for app in app_list:
            app_output = self.handle_app(app, **options)
            if app_output:
                output.append(app_output)
        return '\n'.join(output)

3 View Complete Implementation : admin.py
Copyright GNU Lesser General Public License v3.0
Author : nnseva
def _get_field_rel_model(field):
    import django
    from django.db import models
    if isinstance(field, (models.ForeignKey, models.ManyToManyField)):
        if django.VERSION >= (2, 0):
            return field.remote_field.model
        return field.rel.to

3 View Complete Implementation : unittest.py
Copyright MIT License
Author : zaihui
    @staticmethod
    def mock_field_default(field):
        from django.db import DefaultConnectionProxy

        if field.has_default():
            if callable(field.default):
                if field.default.__name__ == 'now':
                    return datetime.datetime.now()
                return field.default()
            return field.default
        if not field.empty_strings_allowed or \
                (field.null and not DefaultConnectionProxy().features.interprets_empty_strings_as_nulls):
            return None
        return ''

0 View Complete Implementation : run_tests.py
Copyright MIT License
Author : azavea
def create_extension_postgis():
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute('CREATE EXTENSION IF NOT EXISTS postgis')

0 View Complete Implementation : sqldiff.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, app_models, options):
        self.has_differences = None
        self.app_models = app_models
        self.options = options
        self.dense = options.get('dense_output', False)

        try:
            self.introspection = connection.introspection
        except AttributeError:
            from django.db import get_introspection_module
            self.introspection = get_introspection_module()

        self.cursor = connection.cursor()
        self.django_tables = self.get_django_tables(options.get('only_existing', True))
        self.db_tables = self.introspection.get_table_list(self.cursor)
        self.differences = []
        self.unknown_db_fields = {}
        self.new_db_fields = set()
        self.null = {}
        self.unsigned = set()

        self.DIFF_SQL = {
            'error': self.SQL_ERROR,
            'comment': self.SQL_COMMENT,
            'table-missing-in-db': self.SQL_TABLE_MISSING_IN_DB,
            'table-missing-in-model': self.SQL_TABLE_MISSING_IN_MODEL,
            'field-missing-in-db': self.SQL_FIELD_MISSING_IN_DB,
            'field-missing-in-model': self.SQL_FIELD_MISSING_IN_MODEL,
            'fkey-missing-in-db': self.SQL_FKEY_MISSING_IN_DB,
            'fkey-missing-in-model': self.SQL_FIELD_MISSING_IN_MODEL,
            'index-missing-in-db': self.SQL_INDEX_MISSING_IN_DB,
            'index-missing-in-model': self.SQL_INDEX_MISSING_IN_MODEL,
            'unique-missing-in-db': self.SQL_UNIQUE_MISSING_IN_DB,
            'unique-missing-in-model': self.SQL_UNIQUE_MISSING_IN_MODEL,
            'field-type-differ': self.SQL_FIELD_TYPE_DIFFER,
            'field-parameter-differ': self.SQL_FIELD_PARAMETER_DIFFER,
            'notnull-differ': self.SQL_NOTNULL_DIFFER,
        }

        if self.can_detect_notnull_differ:
            self.load_null()

        if self.can_detect_unsigned_differ:
            self.load_unsigned()

0 View Complete Implementation : sqldiff.py
Copyright Apache License 2.0
Author : edisonlz
    def get_field_db_type(self, description, field=None, table_name=None):
        from django.db import models
        # DB-API cursor.description
        #(name, type_code, display_size, internal_size, precision, scale, null_ok) = description
        type_code = description[1]
        if type_code in self.DATA_TYPES_REVERSE_OVERRIDE:
            reverse_type = self.DATA_TYPES_REVERSE_OVERRIDE[type_code]
        else:
            try:
                try:
                    reverse_type = self.introspection.data_types_reverse[type_code]
                except AttributeError:
                    # backwards compatibility for before introspection refactoring (r8296)
                    reverse_type = self.introspection.DATA_TYPES_REVERSE.get(type_code)
            except KeyError:
                reverse_type = self.get_field_db_type_lookup(type_code)
                if not reverse_type:
                    # type_code not found in data_types_reverse map
                    key = (self.differences[-1][:2], description[:2])
                    if key not in self.unknown_db_fields:
                        self.unknown_db_fields[key] = 1
                        self.add_difference('comment', "Unknown database type for field '%s' (%s)" % (description[0], type_code))
                    return None

        kwargs = {}
        if type_code == 16946 and field and getattr(field, 'geom_type', None) == 'POINT':
            reverse_type = 'django.contrib.gis.db.models.fields.PointField'

        if isinstance(reverse_type, tuple):
            kwargs.update(reverse_type[1])
            reverse_type = reverse_type[0]

        if reverse_type == "CharField" and description[3]:
            kwargs['max_length'] = description[3]

        if reverse_type == "DecimalField":
            kwargs['max_digits'] = description[4]
            kwargs['decimal_places'] = description[5] and abs(description[5]) or description[5]

        if description[6]:
            kwargs['blank'] = True
            if reverse_type not in ('TextField', 'CharField'):
                kwargs['null'] = True

        if field and getattr(field, 'geography', False):
            kwargs['geography'] = True

        if '.' in reverse_type:
            from django.utils import importlib
            # TODO: when was importlib added to django.utils ? and do we
            # need to add backwards compatibility code ?
            module_path, package_name = reverse_type.rsplit('.', 1)
            module = importlib.import_module(module_path)
            field_db_type = getattr(module, package_name)(**kwargs).db_type(connection=connection)
        else:
            field_db_type = getattr(models, reverse_type)(**kwargs).db_type(connection=connection)

        tablespace = field.db_tablespace
        if not tablespace:
            tablespace = "public"
        if (tablespace, table_name, field.column) in self.unsigned:
            field_db_type = '%s %s' % (field_db_type, self.unsigned_suffix)

        return field_db_type

0 View Complete Implementation : sqldiff.py
Copyright Apache License 2.0
Author : edisonlz
    def handle(self, *app_labels, **options):
        from django.db import models
        from django.conf import settings

        engine = None
        if hasattr(settings, 'DATABASES'):
            engine = settings.DATABASES['default']['ENGINE']
        else:
            engine = settings.DATABASE_ENGINE

        if engine == 'dummy':
            # This must be the "dummy" database backend, which means the user
            # hasn't set DATABASE_ENGINE.
            raise CommandError("""Django doesn't know which syntax to use for your SQL statements,
because you haven't specified the DATABASE_ENGINE setting.
Edit your settings file and change DATABASE_ENGINE to something like 'postgresql' or 'mysql'.""")

        if options.get('all_applications', False):
            app_models = models.get_models(include_auto_created=True)
        else:
            if not app_labels:
                raise CommandError('Enter at least one appname.')
            try:
                app_list = [models.get_app(app_label) for app_label in app_labels]
            except (models.ImproperlyConfigured, ImportError) as e:
                raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)

            app_models = []
            for app in app_list:
                app_models.extend(models.get_models(app, include_auto_created=True))

        ## remove all models that are not managed by Django
        #app_models = [model for model in app_models if getattr(model._meta, 'managed', True)]

        if not app_models:
            raise CommandError('Unable to execute sqldiff no models founds.')

        if not engine:
            engine = connection.__module__.split('.')[-2]

        if '.' in engine:
            engine = engine.split('.')[-1]

        cls = DATABASE_SQLDIFF_CLastES.get(engine, GenericSQLDiff)
        sqldiff_instance = cls(app_models, options)
        sqldiff_instance.find_differences()
        if not sqldiff_instance.has_differences:
            self.exit_code = 0
        sqldiff_instance.print_diff(self.style)

0 View Complete Implementation : fabfile.py
Copyright MIT License
Author : harvard-lil
@task
def delete_empty_courts(dry_run='true'):
    """
        Delete empty courts, and reslug any other courts that are affected by the newly-available slug.
        NOTE: this may not be a good idea to run if users depend on stable court slugs.
    """
    from django.db import transaction
    import re
    courts_to_delete = set(Court.objects.filter(case_metadatas=None))
    for court_to_delete in sorted(courts_to_delete, key=lambda c: c.slug):
        m = re.match(r'(.*?)(?:-(\d+))?$', court_to_delete.slug)
        prefix, num = m.groups()
        matches = list(Court.objects.filter(slug__startswith=prefix).order_by('slug'))
        reslug = []
        for cc in matches:
            m = re.match(r'%s-(\d+)$' % re.escape(prefix), cc.slug)
            if m and (not num or int(num) < int(m.group(1))) and cc not in courts_to_delete:
                reslug.append(cc)
        with transaction.atomic(using='capdb'):
            if dry_run == 'false':
                print("Deleting %s" % court_to_delete)
                court_to_delete.delete()
            else:
                print("Would delete %s" % court_to_delete)
            for court_to_reslug in reslug:
                if dry_run == 'false':
                    print(" - Reslugging %s" % court_to_reslug)
                    court_to_reslug.slug = None
                    court_to_reslug.save()
                else:
                    print(" - Would reslug %s" % court_to_reslug)

0 View Complete Implementation : conf.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jlmadurga
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models
    # Only look at objects that inherit from Django's base model clast
    if inspect.isclast(obj) and issubclast(obj, models.Model):

        # Ignore abstract models
        if not hasattr(obj._meta, 'fields'):
            return lines

        # Grab the field list from the meta clast
        fields = obj._meta.fields
        
        for field in fields:
            # Decode and strip any html out of the field's help text
            if hasattr(field, 'help_text'):
                help_text = strip_tags(force_unicode(field.help_text))
            else:
                help_text = None

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            if hasattr(field, 'verbose_name'):
                verbose_name = force_unicode(field.verbose_name).capitalize()
            else:
                verbose_name = ""

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

0 View Complete Implementation : conf.py
Copyright MIT License
Author : learningequality
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model clast
    if inspect.isclast(obj) and issubclast(obj, models.Model):
        # Grab the field list from the meta clast
        fields = obj._meta.get_fields()

        for field in fields:
            # Skip ManyToOneRel and ManyToManyRel fields which have no 'verbose_name' or 'help_text'
            if not hasattr(field, "verbose_name"):
                continue

            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_text(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_text(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u":param %s: %s" % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u":param %s: %s" % (field.attname, verbose_name))

            # Add the field's type to the docstring
            if isinstance(field, models.ForeignKey):
                to = field.rel.to
                lines.append(
                    u":type %s: %s to :clast:`~%s`"
                    % (field.attname, type(field).__name__, to)
                )
            else:
                lines.append(u":type %s: %s" % (field.attname, type(field).__name__))

    return lines

0 View Complete Implementation : plugin.py
Copyright GNU Affero General Public License v3.0
Author : maas
    def _ensureConnection(self):
        # If connection is already made close it.
        from django.db import connection

        if connection.connection is not None:
            connection.close()

        # Loop forever until a connection can be made.
        while True:
            try:
                connection.ensure_connection()
            except Exception:
                log.err(
                    _why=(
                        "Error starting: "
                        "Connection to database cannot be established."
                    )
                )
                time.sleep(1)
            else:
                # Connection made, now close it.
                connection.close()
                break

0 View Complete Implementation : resources.py
Copyright GNU Affero General Public License v3.0
Author : maas
def close_all_connections():
    from django.db import connections

    for conn in connections.all():
        conn.close()

0 View Complete Implementation : conf.py
Copyright GNU Affero General Public License v3.0
Author : openpolis
def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model clast
    if inspect.isclast(obj) and issubclast(obj, models.Model):
        # Grab the field list from the meta clast
        fields = obj._meta.get_fields()

        for field in fields:
            if not hasattr(field, "verbose_name"):
                continue

            # Decode and strip any html out of the field's help text
            help_text = strip_tags(force_text(field.help_text))

            # Decode and capitalize the verbose name, for use if there isn't
            # any help text
            verbose_name = force_text(field.verbose_name).capitalize()

            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(":param %s: %s" % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(":param %s: %s" % (field.attname, verbose_name))

            # Add the field's type to the docstring
            lines.append(":type %s: %s" % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines