本文整理汇总了Python中django.db.models方法的典型用法代码示例。如果您正苦于以下问题:Python db.models方法的具体用法?Python db.models怎么用?Python db.models使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db
的用法示例。
在下文中一共展示了db.models方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_has_fields
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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
示例2: reverse_func
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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)
示例3: add_permissions
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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)
示例4: forward_migrate
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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()
示例5: add_permissions
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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)
示例6: remove_permissions
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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)
示例7: forwards_func
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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
示例8: setup
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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
示例9: emit_post_migrate_signal
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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)
示例10: _get_instances
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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
示例11: _handle_redirects_callback
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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')
示例12: register_signals
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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)
示例13: update_queue_models
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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)
示例14: remove_transport_modes_and_approved_fuels
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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()
示例15: delete_query_set_model_objects
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import models [as 别名]
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