Python django.db.models() Examples
The following are 30
code examples of django.db.models().
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
, or try the search function
.
Example #1
Source File: 4679_resource_editor_permissions.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def add_permissions(apps, schema_editor, with_create_permissions=True): db_alias = schema_editor.connection.alias Group = apps.get_model("auth", "Group") Permission = apps.get_model("auth", "Permission") write_nodegroup = Permission.objects.get(codename='write_nodegroup', content_type__app_label='models', content_type__model='nodegroup') delete_nodegroup = Permission.objects.get(codename='delete_nodegroup', content_type__app_label='models', content_type__model='nodegroup') resource_editor_group = Group.objects.using(db_alias).get(name='Resource Editor') resource_editor_group.permissions.add(write_nodegroup) resource_editor_group.permissions.add(delete_nodegroup) resource_editor_group = Group.objects.using(db_alias).get(name='Resource Reviewer') resource_editor_group.permissions.add(write_nodegroup) resource_editor_group.permissions.add(delete_nodegroup) resource_editor_group = Group.objects.using(db_alias).get(name='Crowdsource Editor') resource_editor_group.permissions.add(write_nodegroup) resource_editor_group.permissions.add(delete_nodegroup)
Example #2
Source File: base.py From django-seo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _handle_redirects_callback(model_class, sender, instance, **kwargs): """ Callback to be attached to a pre_save signal of tracked models and create instances of redirects for changed URLs. """ # avoid RuntimeError for apps without enabled redirects from .models import Redirect if not instance.pk: return try: after = instance.get_absolute_url() before = sender.objects.filter(id=instance.id).first().get_absolute_url() if before != after: Redirect.objects.get_or_create( old_path=before, new_path=after, site=Site.objects.get_current(), all_subdomains=True ) except Exception as e: logger.exception('Failed to create new redirect')
Example #3
Source File: base.py From django-seo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _get_instances(cls, path, context=None, site=None, language=None, subdomain=None): """ A sequence of instances to discover metadata. Each instance from each backend is looked up when possible/necessary. This is a generator to eliminate unnecessary queries. """ backend_context = {'view_context': context} for model in cls._meta.models.values(): for instance in model.objects.get_instances( path=path, site=site, language=language, subdomain=subdomain, context=backend_context) or []: if hasattr(instance, '_process_context'): instance._process_context(backend_context) yield instance
Example #4
Source File: sql.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def emit_post_migrate_signal(created_models, verbosity, interactive, db): # Emit the post_migrate signal for every application. for app_config in apps.get_app_configs(): if app_config.models_module is None: continue if verbosity >= 2: print("Running post-migrate handlers for application %s" % app_config.label) models.signals.post_migrate.send( sender=app_config, app_config=app_config, verbosity=verbosity, interactive=interactive, using=db) # For backwards-compatibility -- remove in Django 1.9. models.signals.post_syncdb.send( sender=app_config.models_module, app=app_config.models_module, created_models=created_models, verbosity=verbosity, interactive=interactive, db=db)
Example #5
Source File: manage.py From open-context-py with GNU General Public License v3.0 | 6 votes |
def delete_query_set_model_objects(self, saved_query_sets): """ deletes models from a list of query sets related to the item(s) to be redacted """ del_count = 0 for query_set in saved_query_sets: # we've succeeded in saving the restore data, now delete these items for model_obj in query_set: del_ok = False try: model_obj.delete() del_ok = True except: del_ok = False if del_ok: del_count += 1 return del_count
Example #6
Source File: deletemerge.py From open-context-py with GNU General Public License v3.0 | 6 votes |
def delete_type_records(self, uuid, item_type): """ Deletes records of data specific to models of different types For now, we're not deleting strings, since they may be used on one or more types. """ output = True if item_type == 'subjects': Subject.objects.filter(uuid=uuid).delete() elif item_type == 'media': Mediafile.objects.filter(uuid=uuid).delete() elif item_type == 'documents': OCdocument.objects.filter(uuid=uuid).delete() elif item_type == 'persons': Person.objects.filter(uuid=uuid).delete() elif item_type == 'predicates': Predicate.objects.filter(uuid=uuid).delete() elif item_type == 'types': OCtype.objects.filter(uuid=uuid).delete() else: output = False return output
Example #7
Source File: base.py From django-seo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def register_signals(): for metadata_class in registry.values(): model_instance = metadata_class._meta.get_model('modelinstance') if model_instance is not None: update_callback = functools.partial(_update_callback, model_class=model_instance) delete_callback = functools.partial(_delete_callback, model_class=model_instance) ## Connect the models listed in settings to the update callback. for model in metadata_class._meta.seo_models: # TODO Currently it's not needed to create metadata for new instance models.signals.post_save.connect(update_callback, sender=model, weak=False) models.signals.pre_delete.connect(delete_callback, sender=model, weak=False) if getattr(settings, 'SEO_USE_REDIRECTS', False): redirects_models = import_tracked_models() for model in redirects_models: redirects_callback = functools.partial(_handle_redirects_callback, model_class=model_instance) models.signals.pre_save.connect(redirects_callback, sender=model, weak=False)
Example #8
Source File: base.py From django-seo2 with MIT License | 6 votes |
def register_signals(): for metadata_class in list(registry.values()): model_instance = metadata_class._meta.get_model('modelinstance') if model_instance is not None: update_callback = curry(_update_callback, model_class=model_instance) delete_callback = curry(_delete_callback, model_class=model_instance) # Connect the models listed in settings to the update callback. for model in metadata_class._meta.seo_models: # TODO Currently it's not needed to create metadata for new # instance models.signals.post_save.connect(update_callback, sender=model, weak=False) models.signals.pre_delete.connect(delete_callback, sender=model, weak=False)
Example #9
Source File: 6020_bi_directional_node_to_resource.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def setup(apps): nodes = apps.get_model("models", "Node") tiles = apps.get_model("models", "Tile") relations = apps.get_model("models", "ResourceXResource") resource = apps.get_model("models", "Resource") resource_instance_nodes = { str(node["nodeid"]): node["datatype"] for node in nodes.objects.filter(Q(datatype="resource-instance") | Q(datatype="resource-instance-list")).values( "nodeid", "datatype" ) } resource_instance_tiles = tiles.objects.filter( Q(nodegroup_id__node__datatype="resource-instance") | Q(nodegroup_id__node__datatype="resource-instance-list") ).distinct() root_ontology_classes = { str(node["graph_id"]): node["ontologyclass"] for node in nodes.objects.filter(istopnode=True).values("graph_id", "ontologyclass") } return resource, relations, resource_instance_nodes, resource_instance_tiles, root_ontology_classes
Example #10
Source File: 5476_search_export.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def forwards_func(apps, schema_editor): TileModel = apps.get_model("models", "TileModel") try: basic_search_settings_tile = TileModel.objects.get(tileid="a4e0f0e2-9840-4ba6-acae-a6c430daf917") if basic_search_settings_tile.data["d0987ec0-fad8-11e6-aad3-6c4008b05c4c"] > 10000: basic_search_settings_tile.data["d0987ec0-fad8-11e6-aad3-6c4008b05c4c"] = 10000 basic_search_settings_tile.save() except TileModel.DoesNotExist as e: pass try: CardXNodeXWidget = apps.get_model("models", "CardXNodeXWidget") basic_search_settings_card = CardXNodeXWidget.objects.get(pk="ec6bc4ae-2e9f-11e7-86ec-14109fd34195") basic_search_settings_card.label = "Max number of search results to export (see help for limitations on this value)" basic_search_settings_card.config["label"] = "Max number of search results to export (see help for limitations on this value)" basic_search_settings_card.save() except CardXNodeXWidget.DoesNotExist as e: pass
Example #11
Source File: 4679_resource_editor_permissions.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def remove_permissions(apps, schema_editor, with_create_permissions=True): db_alias = schema_editor.connection.alias Group = apps.get_model("auth", "Group") Permission = apps.get_model("auth", "Permission") write_nodegroup = Permission.objects.get(codename='write_nodegroup', content_type__app_label='models', content_type__model='nodegroup') delete_nodegroup = Permission.objects.get(codename='delete_nodegroup', content_type__app_label='models', content_type__model='nodegroup') resource_editor_group = Group.objects.using(db_alias).get(name='Resource Editor') resource_editor_group.permissions.remove(write_nodegroup) resource_editor_group.permissions.remove(delete_nodegroup) resource_editor_group = Group.objects.using(db_alias).get(name='Resource Reviewer') resource_editor_group.permissions.remove(write_nodegroup) resource_editor_group.permissions.remove(delete_nodegroup) resource_editor_group = Group.objects.using(db_alias).get(name='Crowdsource Editor') resource_editor_group.permissions.remove(write_nodegroup) resource_editor_group.permissions.remove(delete_nodegroup)
Example #12
Source File: 6019_node_config_for_resource_instance.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def forward_migrate(apps, schema_editor, with_create_permissions=True): nodes = apps.get_model("models", "Node") datatypes = apps.get_model("models", "DDataType") for datatype in datatypes.objects.filter(datatype__in=["resource-instance", "resource-instance-list"]): datatype.defaultconfig = {"graphs": []} datatype.save() for node in nodes.objects.filter(datatype__in=["resource-instance", "resource-instance-list"]): old_config = node.config new_config = {"graphs": []} if old_config["graphid"]: for graphid in old_config["graphid"]: new_config["graphs"].append({"graphid": graphid, "ontologyProperty": "", "inverseOntologyProperty": ""}) node.config = new_config node.save()
Example #13
Source File: 2891_tile_qa_schema.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def add_permissions(apps, schema_editor, with_create_permissions=True): db_alias = schema_editor.connection.alias Group = apps.get_model("auth", "Group") Permission = apps.get_model("auth", "Permission") User = apps.get_model("auth", "User") resource_reviewer_group = Group.objects.using(db_alias).create(name='Resource Reviewer') read_nodegroup = Permission.objects.get(codename='read_nodegroup', content_type__app_label='models', content_type__model='nodegroup') resource_reviewer_group.permissions.add(read_nodegroup) try: admin_user = User.objects.using(db_alias).get(username='admin') admin_user.groups.add(resource_reviewer_group) print('added admin group') except Exception as e: print(e)
Example #14
Source File: 0009_4_0_1.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def reverse_func(apps, schema_editor): Node = apps.get_model("models", "Node") Function = apps.get_model("models", "Function") FunctionXGraph = apps.get_model("models", "FunctionXGraph") required_nodes_function = Function.objects.get(pk='60000000-0000-0000-0000-000000000002') graphs = {} required_nodes = Node.objects.filter(isrequired = True) for node in required_nodes: if str(node.graph_id) not in graphs: graphs[str(node.graph_id)] = {} if str(node.nodegroup_id) not in graphs[str(node.graph_id)]: graphs[str(node.graph_id)][str(node.nodegroup_id)] = [] graphs[str(node.graph_id)][str(node.nodegroup_id)].append(str(node.pk)) node.isrequired = False node.save() for graph_id, required_nodes in graphs.items(): function_config = { "required_nodes": JSONSerializer().serialize(required_nodes), "triggering_nodegroups": list(required_nodes.keys()) } FunctionXGraph.objects.create(function=required_nodes_function, graph_id=graph_id, config=function_config)
Example #15
Source File: 0008_auto_20160421_1648.py From scale with Apache License 2.0 | 6 votes |
def update_queue_models(apps, schema_editor): # Go through all of the queue models and update their new job and configuration fields Queue = apps.get_model('queue', 'Queue') total_count = Queue.objects.all().count() print 'Updating %s queue models' % str(total_count) done_count = 0 for queue in Queue.objects.select_related('job_exe__job').iterator(): if done_count % 1000 == 0: percent = (done_count / total_count) * 100.00 print 'Completed %s of %s queue models (%f%%)' % (done_count, total_count, percent) done_count += 1 queue.job_id = queue.job_exe.job_id queue.configuration = queue.job_exe.job.configuration queue.save() print 'All %s queue models completed' % str(total_count)
Example #16
Source File: 0093_initial_transport_modes_and_approved_fuels.py From tfrs with Apache License 2.0 | 6 votes |
def remove_transport_modes_and_approved_fuels(apps, schema_editor): """ Remove initial transport modes and approved fuels """ db_alias = schema_editor.connection.alias # By retrieving the models via apps.get_model, we get one appropriately # versioned for this migration (so this shouldn't ever need to be # maintained if fields change) transport_mode = apps.get_model('api', 'TransportMode') transport_mode.objects.using(db_alias).filter( name__in=["Truck", "Rail", "Marine", "Adjacent", "Pipeline"]).delete() approved_fuel = apps.get_model('api', 'ApprovedFuel') approved_fuel.objects.using(db_alias).filter( name__in=approved_fuel_names).delete()
Example #17
Source File: test_serializers.py From figures with MIT License | 6 votes |
def test_has_fields(self): '''Verify the serialized data has the same keys and values as the model Django 2.0 has a convenient method, 'Cast' that will simplify converting values: https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#cast This means that we can retrieve the model instance values as a dict and do a simple ``assert self.serializer.data == queryset.values(...)`` ''' data = self.serializer.data # Hack: Check date and datetime values explicitly assert data['date_for'] == str(self.metrics.date_for) assert dateutil_parse(data['created']) == self.metrics.created assert dateutil_parse(data['modified']) == self.metrics.modified check_fields = self.expected_results_keys - self.date_fields - set(['site']) for field_name in check_fields: db_field = getattr(self.metrics, field_name) if type(db_field) in (float, Decimal, ): assert float(data[field_name]) == pytest.approx(db_field) else: assert data[field_name] == db_field
Example #18
Source File: test_serializers.py From figures with MIT License | 6 votes |
def test_has_fields(self): '''Verify the serialized data has the same keys and values as the model Django 2.0 has a convenient method, 'Cast' that will simplify converting values: https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#cast This means that we can retrieve the model instance values as a dict and do a simple ``assert self.serializer.data == queryset.values(...)`` ''' data = self.serializer.data # Hack: Check date and datetime values explicitly assert data['date_for'] == str(self.site_daily_metrics.date_for) assert dateutil_parse(data['created']) == self.site_daily_metrics.created assert dateutil_parse(data['modified']) == self.site_daily_metrics.modified check_fields = self.expected_results_keys - self.date_fields - set(['site']) for field_name in check_fields: assert data[field_name] == getattr(self.site_daily_metrics,field_name)
Example #19
Source File: mixins.py From django-linguist with MIT License | 5 votes |
def delete_translations(self, language=None): """ Deletes related translations. """ from .models import Translation return Translation.objects.delete_translations(obj=self, language=language)
Example #20
Source File: mixins.py From django-linguist with MIT License | 5 votes |
def _get_concrete_fields_with_model(self): """For compatibility with Django<=1.10. Replace old `_meta.get_concrete_fields_with_model`. https://docs.djangoproject.com/en/1.10/ref/models/meta/ """ return [ (f, f.model if f.model != self.model else None) for f in self.model._meta.get_fields() if f.concrete and ( not f.is_relation or f.one_to_one or (f.many_to_one and f.related_model) ) ]
Example #21
Source File: mixins.py From django-linguist with MIT License | 5 votes |
def get_translations(self, language=None): """ Returns available (saved) translations for this instance. """ from .models import Translation if not self.pk: return Translation.objects.none() return Translation.objects.get_translations(obj=self, language=language)
Example #22
Source File: 0008_set_last_update.py From baobab with GNU General Public License v3.0 | 5 votes |
def forwards(self, orm): "Set last_update field for each event" # Note: Don't use "from appname.models import ModelName". # Use orm.ModelName to refer to models in this application, # and orm['appname.ModelName'] for models in other applications. for event in orm.Event.objects.all(): if event.date_end: event.last_update = event.date_end elif event.eventlogs.exists(): event.last_update = event.eventlogs.all()[0].date elif event.date_start > now(): event.last_update = now() event.save()
Example #23
Source File: mixins.py From django-linguist with MIT License | 5 votes |
def available_languages(self): """ Returns available languages. """ from .models import Translation return ( Translation.objects.filter( identifier=self.linguist_identifier, object_id=self.pk ) .values_list("language", flat=True) .distinct() .order_by("language") )
Example #24
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): self.pre_delete_senders = [] self.post_delete_senders = [] for sender in self.senders: models.signals.pre_delete.connect(self.pre_delete_receiver, sender) models.signals.post_delete.connect(self.post_delete_receiver, sender)
Example #25
Source File: base.py From django-seo2 with MIT License | 5 votes |
def _get_instances(cls, path, context=None, site=None, language=None): """ A sequence of instances to discover metadata. Each instance from each backend is looked up when possible/necessary. This is a generator to eliminate unnecessary queries. """ backend_context = {'view_context': context} for model in cls._meta.models.values(): for instance in model.objects.get_instances(path, site, language, backend_context) or []: if hasattr(instance, '_process_context'): instance._process_context(backend_context) yield instance
Example #26
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def test_only_and_defer_usage_on_proxy_models(self): # Regression for #15790 - only() broken for proxy models proxy = Proxy.objects.create(name="proxy", value=42) msg = 'QuerySet.only() return bogus results with proxy models' dp = Proxy.objects.only('other_value').get(pk=proxy.pk) self.assertEqual(dp.name, proxy.name, msg=msg) self.assertEqual(dp.value, proxy.value, msg=msg) # also test things with .defer() msg = 'QuerySet.defer() return bogus results with proxy models' dp = Proxy.objects.defer('name', 'text', 'value').get(pk=proxy.pk) self.assertEqual(dp.name, proxy.name, msg=msg) self.assertEqual(dp.value, proxy.value, msg=msg)
Example #27
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def setUp(self): self.pre_delete_senders = [] self.post_delete_senders = [] for sender in self.senders: models.signals.pre_delete.connect(self.pre_delete_receiver, sender) models.signals.post_delete.connect(self.post_delete_receiver, sender)
Example #28
Source File: tests.py From django-sqlserver with MIT License | 5 votes |
def tearDown(self): for sender in self.senders: models.signals.pre_delete.disconnect(self.pre_delete_receiver, sender) models.signals.post_delete.disconnect(self.post_delete_receiver, sender)
Example #29
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_only_and_defer_usage_on_proxy_models(self): # Regression for #15790 - only() broken for proxy models proxy = Proxy.objects.create(name="proxy", value=42) msg = 'QuerySet.only() return bogus results with proxy models' dp = Proxy.objects.only('other_value').get(pk=proxy.pk) self.assertEqual(dp.name, proxy.name, msg=msg) self.assertEqual(dp.value, proxy.value, msg=msg) # also test things with .defer() msg = 'QuerySet.defer() return bogus results with proxy models' dp = Proxy.objects.defer('name', 'text', 'value').get(pk=proxy.pk) self.assertEqual(dp.name, proxy.name, msg=msg) self.assertEqual(dp.value, proxy.value, msg=msg)
Example #30
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): self.pre_delete_senders = [] self.post_delete_senders = [] for sender in self.senders: models.signals.pre_delete.connect(self.pre_delete_receiver, sender) models.signals.post_delete.connect(self.post_delete_receiver, sender)